texts: Problems integrating Reed Switch and Solenoid Lock in Arduino Code

texts:
I am trying to integrate solenoid lock, reed switch in my Arduino Code. The flow that I am trying to achieve is - first, the solenoid lock is set to LOW and then the program checks if reed switch is High or Low. Only if its High I want to proceed further. However, even when the reed switch is HIGH the program is not executing further. Here is my code below:

    #include<HX711_ADC.h>
    #include<math.h>

    //pins for lock
    int solenoidPin = 7;

    //pins for reed switch
    int reedSwitch = 2;
    bool reedSwitchStatus;

    //pin for led
    int led_pin= 9;

    void setup()
    {
      Serial.begin(38400);
      pinMode(solenoidPin, OUTPUT);
      pinMode(reedSwitch, INPUT);

      doorUnlock();
    }

    void loop()
      {}

    void doorUnlock()
    {
      digitalWrite(solenoidPin, LOW);
      delay(5000);
      checkReedSwitchStatus();
    }

    void checkReedSwitchStatus()
    {
      reedSwitchStatus = digitalRead(reedSwitch);

      if(reedSwitchStatus == 1)
      {
        Serial.println("Beginning Transaction");
        beginTransaction();
        }
      if (reedSwitchStatus == 0)
        {
          Serial.println("Ending trasaction");
          endTransaction();
          }
      }
      void beginTransaction()
      {
      digitalWrite(led_pin, HIGH);
      delay(500);
      digitalWrite(led_pin, LOW);
      delay(500);
      }

My issue is the beginTransaction function is never executed. Serial monitor continuously prints 'Beginning Transaction'. Attached the screenshot of the serial monitor. Please suggest me what is the error in my code. Thanks in advance!


texts: Is this the right way to blink a character on LCD?

texts:
The code is this:

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

LiquidCrystal_I2C lcd(0x27, 16, 2);

unsigned long blinkTime = 0;
int ValueA = 22;
String placeHolder = "  ";

void setup() {
  lcd.begin();
}

void loop() {
  lcd.setCursor(7, 0);
  if (millis() - blinkTime > 2000) {
    lcd.print(ValueA);
    blinkTime = millis();
  }
  if (millis() - blinkTime > 1000) {
    lcd.print(placeHolder);
  }
}

The I2C LCD library have a lcd.blink() function but it seems that only blinks a "cursor".

The problem with above code is the placeHolder, what if ValueA gets bigger than 2 digits?

Is there a better way to blink a value on LCD?


texts: How to completely clear everything from an arduino and print something new?

texts:
I'm in progress of making a stickman rush game, Until I hit a bug that I have been stuck on. I want to make a if statement that states "If the stickman and the object are in the same place, clear everything and print "Game over." But when i do this, the object is still there. I tried using "lcd.clear()" but it doesnt seem to affect anything. Is there another way to fix this?
Code:
#include <LiquidCrystal.h>

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

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

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

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

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

int screenWidth = 16;
int screenHeight = 2;

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

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

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

  lcd.createChar(1, gameObstical);

}

void loop() {

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

  int obsticalPosition2 = 0;
  int obsticalRow2 = 0;

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

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

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

    if (mapX > 200) {

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

    } else if (mapX < -200) {

      stickManRow = 1;

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

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

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

      }

      if (obsticalPosition == 12) {

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

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

Any ideas? Thanks for reading.


texts: Do external battery packs need to connect to ground on the arduino?

texts: I am going to be controlling 2 servo motors with an arduino. I will use an external battery pack for power. Do I need to connect the negative of the battery to ground on the arduino? If I just use the battery pack to power an LED, it works without connecting it to ground. Can someone please explain the logic behind this in simple wording? Thank you


texts: No known conversion for argument 1 from 'Object*' to 'int*'

texts:
I'm terrible with pointers and need help passing an object to a library I'm writing. I'm getting the error no known conversion for argument 1 from 'LCDMenuItem*' to 'int*' when I try to compile. How do I pass a pointer to an object to a function?

LCDMenu.h

class LCDMenu {
    public:
    bool addItem(LCDMenuItem &item);
    private:
    LCDMenuItem *menuItems[MAX_ITEMS];
    uint8_t itemCount;
};

class LCDMenuItem {
    public:
    LCDMenuItem(char *name);
    bool setFunction(void (*function)(void));
    private:
    bool callFunction() const;
    void (*_function)(void);
    char *name;
};

LCDMenu.cpp

bool LCDMenu::addItem(LCDMenuItem &item) {
    menuItems[itemCount] = &item;
    ...
}

MySketch.ino

LCDMenuItem menuItem("Menu Option");
void setup() {
    menu.addItem(menuItem);
}

When trying to compile

bool addItem(LCDMenuItem *item);
     ^

  no known conversion for argument 1 from 'LCDMenuItem*' to 'int*'


texts:
I am using an Adafruit Trinket M0 to program a small game and would like to save the game state every so often. I am programming it through the Arduino IDE as the chip does not have enough space to run my game with circuitpython (too many libraries). Does the Trinket M0 have any form of persistent storage that I can use, or will I need to use a different device?

I couldn't find EEPROM in the documentation, but I wasn't able to find a definitive answer whether or not it has any form of long term storage. Knowing the board is based on the Attiny85 I would expect it to have 512 bytes or so, but the arduino library is giving me problems when I try to use it as well, so there is no way for me to trial and error this.


texts:
I am new to Arduino programming and currently working on this instructable
http://www.instructables.com/id/Control-Led-RGB/ (following this diagram http://cdn.instructables.com/F6Q/IMHF/I0LCDK6B/F6QIMHFI0LCDK6B.LARGE.jpg)

I have ordered these parts as well.

Arduino Nano: www.ebay.in/itm/Arduino-Nano-SOLDERED-PINS-V3-0-ATmega328-CH340G-BUY-2-GET-1-USB-CABLE-FREE-/172117729247?
HC-05: www.amazon.in/Bluetooth-Transceiver-Module-TTL-Outputs-HC05/dp/B00R95Y0AK?ie=UTF8&psc=1&redirect=true&ref_=ox_sc_act_title_2&smid=A1NDZY44BCNIQJ

My questions are:

Is there need to add voltage divider? If yes can you please provide link?
Can I connect two 5050 RGB modules?
Will 12 V, 1 A will be enough to power this board.


texts: Save some arduino pins when driving a 4 digits 7 segments display

texts:
I built a simple clock using a 4 digits 7 segments LCD display. I display one digit at a time, switching on and off very quicky and cycling through digits.

Everything is ok, but I used 8 + 4 = 12 arduino pins. I need 2 more pins for other features and I don't want to use 0 and 1 as I need onboard programming features of Arduino Mini.

I used I2C for RTC clock, I could add some interface here (like a PCF8574) and get some pins from here. But I'd like a different (and more educational, for me) approach.

Is there an IC that sends an HIGH output on one of four output pins driven by 2 input pins? I need this:

IN     OUT
P0 P1  D0 D1 D2 D3
0  0   1  0  0  0
0  1   0  1  0  0
1  0   0  0  1  0
1  1   0  0  0  1

This way I can connect OUT to digit selection and spare 2 pins.

Thanks for your hints.


texts: ESP8266 wakeup from deep sleep: Both by timer and button?

texts:
In a project powered by batteries, the ESP8266 should go to deep sleep for long time, having RF disabled. After some number of sleep cycles, it shall restart with RF enabled, synchronize time via NTP, and again go to sleep. Think this could work with a counter saved in RTC Memory or SPIFFS.
Additionally, s.o. should be able to wake up via push button (at any time), which should result in different behaviour (running as WiFi AP, allowing for configuration of new WiFi credentials).
The question is: Is it possible to find out what did wake the ESP (timer or pushbutton)?
Edit: Using external circuitry this might be possible. To avoid this, we switch to ESP32, which is an overkill for the project, but easy to find out the source of the wakeup (and with the possibility to use touch sensors). Additionally, ESP32 allows for easy use of "Preferences" in NVR and variables in RTC memory (when using the Arduino IDE), which will survive deep sleep (RTC) and even reset/power loss (NVR).


texts: Serial.read() is getting a whole string rather than just a character?

texts:
From the arduino documentation, the Serial.read() function is supposed to return a single character at a time from incoming serial messages. So if I program the arduino with the following:

#include "SPI.h"

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

void loop() {
  if (Serial.available() > 0) {
    char data1 = Serial.read();
    Serial.print(data1);
  }
}

And I open the serial monitor and send "Hello, World!" I would expect the received message to be the individual characters printed one at time but instead I get back the whole message. So what gives? What am I not understanding?


texts: Deriving the exact relationship between PWM and steering

texts:
I am using a L298n driver to make a basic RC car. I realise that PWM is used to control the speed of the motors and that the car would turn when the wheels on one side of the car have a rpm different from the other side. I am taking user input from the x-axis of a joystick.
However, I am not sure how to arrive at an exact relationship between rpm and the angle by which the car turns.
My approach so far :

If the car is turning left, the wheels on the left side are turning in a smaller arc and hence the inner wheels have a lower rpm. The sharper the turn the slower the inner wheels turn.

PWM is used to control the speed of the motors.

Each angle of turning corresponds to circles of different radii. Hence a sharper turn would correspond to a circle with a very small radius.

So I need to map the x-axis values of the analog stick to angles by which I want the car to turn. Once I know the relation between rpm and the angle by which the car turns, I can map the joystick values to PWM values.

This question has already been asked here and the consensus seems to be that some sort of feedback mechanism is required for an exact calibration.
I have two questions :

Where do I learn more about this feedback mechanism?
Purely from a physics perspective, considering an ideal environment, how do I derive a relation between rpm and the steering angle?


texts:
I'm looking for my Arduino board to jump to a function based on an if condition, where a string (content) is checked to see if it matches the word FALLEN. However, the if condition never occurs regardless of which way I phrase the condition.

/*****************************************************************
XBee_Serial_Passthrough.ino

Set up a software serial port to pass data between an XBee Shield
and the serial monitor.

Hardware Hookup:
  The XBee Shield makes all of the connections you'll need
  between Arduino and XBee. If you have the shield make
  sure the SWITCH IS IN THE "DLINE" POSITION. That will connect
  the XBee's DOUT and DIN pins to Arduino pins 2 and 3.
*****************************************************************/
// We'll use SoftwareSerial to communicate with the XBee:
#include <AltSoftSerial.h>
#include <GSM.h>

#define PINNUMBER ""

//AltSoftSerial altSerial;

// XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
AltSoftSerial XBee(8, 9); // RX, TX

GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;

String parse="FALLEN";

void setup()
{
  // Set up both ports at 9600 baud. This value is most important
  // for the XBee. Make sure the baud rate matches the config
  // setting of your XBee.
  XBee.begin(9600);
  Serial.begin(9600);

  Serial.println("SMS Messages Sender");

  boolean notConnected = true;

  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
}

void loop()
{
  /*if (Serial.available())
  { // If data comes in from serial monitor, send it out to XBee
    XBee.write(Serial.read());
  }
  if (XBee.available())
  { // If data comes in from XBee, send it out to serial monitor
    Serial.write(XBee.read());
  }*/

  String content = "";
  char character;

while(XBee.available()) {
      character = XBee.read();
      content.concat(character);
      delay (10);
  }

if (content != "") {
    Serial.println(content); //Serial monitor to show content (FALLEN).

    if(content=="FALLEN"){ //Check if content is "FALLEN", if true, jump to void sos().
      Serial.println("DSTOM"); //Check if the if statement even runs.
      sos();
    }

  }

}

void sos(){

  Serial.println("DSOTM");
  //readSerial(remoteNumber);

 // int phone = 97308124;
  char remoteNumber[20] = "97308124";
 // String number;
 // number=String(phone);
 // number.toCharArray(remoteNumber,20);

  char txtMsg[200] = "SENTBOYS";
//  String talk = "SENTBOYS";

//  talk.toCharArray(txtMsg,200);

  sms.beginSMS(remoteNumber);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");

}

I have tried different syntax of string checking including "content==parse", "content.equals(parse)" and "content=="FALLEN";

Any help will be greatly appreciated.

EDIT: I fixed it by using a character instead of a string.

//  String content = "";
  char character;

  char parse='N';

while(XBee.available()) {
      character = XBee.read();
     // content.concat(character);
      delay (10);
      Serial.print(character);
      Serial.print(character);

      if(character=='N'){

        Serial.println("DSTOM");

      }

In this case, the characters a printed 1 by 1 (with a small delay between each character).


texts:
The following image is my connection of l298 with Arduino.

This is the program.

int ENA = 10; // MCU PWM Pin 10 to ENA on L298n Board
int IN1 = 9;  // MCU Digital Pin 9 to IN1 on L298n Board
int IN2 = 8;  // MCU Digital Pin 8 to IN2 on L298n Board

int ENB = 5;  // MCU PWM Pin 5 to ENB on L298n Board
int IN3 = 7;  // MCU Digital pin 7 to IN3 on L298n Board
int IN4 = 6;  // MCU Digital pin 6 to IN4 on L298n Board

void setup()
{

pinMode(ENA, OUTPUT); //Set all the L298n Pin to output
pinMode(ENB, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
}
void DRIVEONE()
{
// Run the motors on both direction at fixed speed
digitalWrite(IN1, HIGH); // Turn HIGH motor A
digitalWrite(IN2, LOW);
analogWrite(ENA, 200); // TO set the turning speed to 200 out of possible
range 0 to 255

digitalWrite(IN3, HIGH); // turn HIGH motor B
digitalWrite(IN4, LOW);  // To set the turning speed to 200 out of possible
range 0 to 255
analogWrite(ENB, 200);
delay(2000);  // Delay to 2 seconds
void loop()
{
DRIVEONE();
delay(100);
}

The program seems to work fine but the motors run only when I touch all the 15 pins in L298 as shown in the second image.
I don't understand why the motors aren't running without touching those 15 pins.

I have connected the L298 to a 12V rechargeable battery and Arduino to a 9V battery.
Please help me understand what is wrong here.
Thank you.


texts: How do I listen for a sound that matches a pre-recorded sound?

texts:
I'm working on a project that uses an Arduino Uno to listen for a bell ring and then uploads to a web server the exact time the bell was rung using a WiFi Shield.

I want to know how I can listen for the bell ring (a three second long high pitch tone) and be able to detect that that's what the Arduino heard. I think the best way may be to pre-record the sound and then the Arduino will constantly try to match the incoming sounds to the prerecorded sound. I'm wondering how I could go about doing this (or are there better methods).

The bell sounds kind of like this: bell sound


texts: How to get the firmware (hex) file from a .ino file containing the code

texts:
I currently have a .ino firmware file that I use in the Arduino IDE to program an ATmega328 micro-controller. I would like to get the file that the Arduino IDE uses to program the micro-controller.

Probably the IDE uses a hexadecimal (hex) file or something and sends it to the micro-controller through the serial.

How can I get this file being the only file that the IDE generates is the .ino?


texts: Why does exit status 1 stray '\302' in program pop up around Serial.println ( "-> Second Service load");?

texts:
/*
 Controlling a servo position using a potentiometer (variable resistor)
 by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

 modified on 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Knob
*/

#include <Wire.h>
#include "ds3231.h"
#include <Servo.h>
int potpin = 0; // Analog pin is used to connect the potentiometer
int val; // Variable to read the value from the analog pin
int pause = 800; // Delay in open feeders (feed amount)

Servo myservo;  // create servo object to control a servo

#define BUFF_MAX 256

// First Service
uint8_t wake_HOUR1 = 12;
uint8_t wake_MINUTE1 = 56;
uint8_t wake_SECOND1 = 0;

// Second Service
uint8_t wake_HOUR2 = 18;
uint8_t wake_MINUTE2 = 30;

// How often to update the information to the standard output (ms)
unsigned long prev = 5000, interval = 5000;

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write (0); // Set the position to 0

  Serial.begin (9600);
  Wire.begin ();
  DS3231_init (DS3231_INTCN);
  DS3231_clear_a1f ();
  DS3231_clear_a2f ();
  set_alarm ();
}

void loop()
{
   char buff [BUFF_MAX];
  unsigned long now = millis ();
  struct ts t;

  // Output through time (5000ms) The time and alarm clocks ustanovlennnye
  if ((now - prev> interval) && (Serial.available () <= 0)) {
    DS3231_get (& t);

    // Display current time
    snprintf (buff, BUFF_MAX, ".% d% 02d% 02d% 02d:.% 02d:% 02d", t.year,
             t.mon, t.mday, t.hour, t.min, t.sec);
    Serial.println (buff);

    // Display a1 debug info
    DS3231_get_a1 (& buff [0], 59);
    Serial.println (buff);
    DS3231_get_a2 (& buff [0], 59);
    Serial.println (buff);

    if (DS3231_triggered_a1 ()) {
      // INT has been pulled low
      Serial.println ( "-> First Service load");

  myservo.write(10);                  // sets the servo position according to the scaled value
  delay(1000);                           // waits for the servo to get there
  myservo.write(170);                  // sets the servo position according to the scaled value
  delay(1000);                           // waits for the servo to get there

      // Clear a1 alarm flag and let INT go into hi-z
      DS3231_clear_a1f ();
    }
    if (DS3231_triggered_a2 ()) {
      // INT has been pulled low
      Serial.println ( "-> Second Service load");

  myservo.write(10);                  // sets the servo position according to the scaled value
  delay(1000);                           // waits for the servo to get there
  myservo.write(170);                  // sets the servo position according to the scaled value
  delay(1000);
}


texts: Arduino UNO and RS485 Communication Problem

texts:
I am learning Arduino, a beginner in programming. I want to use Arduino UNO to connect a wind direction sensor RS485. The problem is the output in the serial monitor, the return data from the wind direction sensor is unstable.

I need to get the return data from the wind direction sensor to get the wind direction. From the factory manual, they said sent a data to the sensor: 0x01 0x03 0x00 0x00 0x00 0x02 0xC4 0x0B and the sensor will return, like 0x01 0x03 0x04 0x06 0x48 0x00 0xA0 0x7A 0xD5

The wind direction dat at the above 5 and 6 position, the 0x00 0xA0 => 00A0H(HEX)=160 degree.

Tools:
Arduino Uno Board

Wind Direction Sensor
http://www.jnrsmcu.com/equipment/299.html

RS485 Board (3.3V)
https://www.waveshare.com/rs485-board-3.3v.htm

The following is my coding:

#include <SoftwareSerial.h>

SoftwareSerial RS485Serial(10, 11); // RX, TX

void setup()
{
    RS485Serial.begin(4800);   // set the data rate
    Serial.begin(4800);
    Serial.println("Start");

    pinMode(12, OUTPUT);
    digitalWrite(12, HIGH);  // Init Transceiver
}

byte buf[8];

int byteReceived;

void loop()
{
    digitalWrite(12, HIGH);

    byte wind[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
    RS485Serial.write(wind, sizeof(wind));
    Serial.flush();
    RS485Serial.flush();
    // Serial.print(wind[0], HEX);
    Serial.println("Send");

    digitalWrite(12, LOW);
    delayMicroseconds(200);

    RS485Serial.readBytes(buf, 8);
    delay(10);
    Serial.println(buf[0], HEX);
    Serial.println(buf[5], HEX);
    Serial.println(buf[6], HEX);
    Serial.flush();
    RS485Serial.flush();
    delay (1000);
}

Connection map:


texts: Circuit works on breadboard but has power problems on protoboard

texts:
I'm building a simple circuit that takes data from an IMU (using MPU6050), sends it to a microprocessor (Arduino Pro Mini 5V) to apply data smoothing and averaging, and then this data is sent using an HC-08 BLE module for the data to be further processed on a mobile. The circuit is powered by a 9V battery (6LR61) connected to RAW (Vin on other Arduino boards).

When I build this circuit on a breadboard, it works well, but the Arduino is power hungry as expected. It runs for over an hour in this setting (I haven't tested it for longer), but I've build this circuit twice using protoboards and it can't stay on. One circuit is able to send data for a while, but the LED on my BLE module dims and eventually turns off after ~5m, and requires me to wait 30+m before I try to power the circuit again. The other circuit has all LEDs shine when power is switched on, but the IMU doesn't send any data (an LED on the Pro Mini blinks whenever I2C data is received).

The shitty thing is that, whenever I power these circuits via USB, they work as intended, just like when I power them using 9V to RAW on the breadboard.

I tested the circuit on the breadboard later and after BLE has connected and is sending data, the whole circuit draws 42.9mA, the BLE module draws 1.5mA, and the IMU draws 5.4mA.

What is the most effective way to fix this problem? Should I focus on finding a different battery, or focus on power-savings within the circuit?

These are my ideas so far:

replace all boards with 3.3V versions
reduce clock speed (might not be viable, I need a lot of IMU data?)
use external voltage regulator, connect Vout from regulator to 5V of pro mini
replace 9V battery with Lithium Ion battery
replace Pro Mini with an ATtiny85

I'd like to take the least time to maximize power savings, so while I could go through all these ideas, I just need the circuit to work at the end of the day.


texts:
I get this error when I try to compile and upload the code for the ESP826612E

fork/exec /home/c/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++: exec format error

I don't understand what the problem is, It was working fine for days until today.

Anyone has solutions?


texts: How can I get my LCD display to display Chinese and Japanese characters?

texts:
I'm making a project that requires me to display Chinese and Japanese characters on an LCD. However, the 16x2 LCD display I have does not seem to support displaying Chinese and Japanese characters.
If I do something like lcd.print("おはよう世界"); or lcd.print("简体中文测试");, it seems to display just a bunch of jumbled random characters (which I am assuming have their character values add up to the values of the characters in the code).
How can I get my LCD to display Chinese and Japanese characters?
Or, if there's no way to do it without buying a new one that supports it, where can I buy one?


texts: how to use capacitive touch keypad without using CapacitiveSensor.h Library

texts: i want to use multiple capacitive touch keypads with arduino uno but number of IO ports are not enough. So I decided to use MSP23S17 port extender. Now i have to find some methods to sense the touch keypad without using its library. Can anyone tell me if there is any way to do the task.


texts:
I have the following code

#include <SoftwareSerial.h>

byte RX = 10;
byte TX = 11;
SoftwareSerial *A7board = new SoftwareSerial(RX, TX);

void print_result()
{
  Serial.print("A7 board info: ");
  while( A7board->available() != 0)
    Serial.write( A7board->read());
  Serial.println();
}

void setup() {
  Serial.begin(115200);
  A7board->begin(115200);
  delay(200);

  Serial.println("Send AT command");
  A7board->println("AT");
  delay(25000);
  print_result();

  Serial.println("AT+GPS turn on");
  A7board->println("AT+GPS=1");
  delay(10000);
  print_result();

  Serial.println("AT+GPSRD turn on");
  A7board->println("AT+GPSRD=1");
  delay(10000);
  print_result();

}

void loop() {
  print_result();
  delay(2000);
}

This is the AI Thinker A7 documentation (I googled it): http://www.communica.co.za/Content/Catalog/Documents/D1266435144.pdf?fbclid=IwAR0TmqhxMILHbgxFfsKIa5bPz3LuCFoi8JbwcQyTXEhiCe7Q-AYrzd2-T1I

This is the wiring.

But I am not getting any data.

Output:

What mistake am I making? I cannot get it running. (PS: I am a newbie in electronics.)


texts:
Having this  error-
Arduino: 1.8.8 Hourly Build 2018/11/30 12:33 (Windows 10), Board: "Arduino/Genuino Uno"

open sketch\LCD.ino.cpp: Access is denied.
Error compiling for board Arduino/Genuino Uno.

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


texts: Can anyone explain how this code can be converted to work on a Arduino Uno

texts:
I was hoping someone could help, im totally new to this. I wish to use this code for a Raspberry Pi on an Arduino Uno with the Adafruit SD data logging shield. It is for recording reed switch closures on a tipping bucket rain gauge. The interrupt and bounce time are to allow program interrupts and false tip suppression. I am looking to tie it in with the RTC and SD storage options on the Arduino. Any help appreciated.

#!/usr/bin/python3
import RPi.GPIO as GPIO
import time

# this many mm per bucket tip
CALIBRATION = 0.200
# which GPIO pin the gauge is connected to
PIN = 17
# file to log rainfall data in
LOGFILE = "log.csv"

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# variable to keep track of how much rain
rain = 0

# the call back function for each bucket tip
def cb(channel):
    global rain
    rain = rain + CALIBRATION

# register the call back for pin interrupts
GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=300)

# open the log file
file = open(LOGFILE, "a")

# display and log results
while True:
    line = "%i, %f" % (time.time(), rain)
    print(line)
    file.write(line + "\n")
    file.flush()
    rain = 0
    time.sleep(5)

# close the log file and exit nicely
file.close()
GPIO.cleanup()


texts: Recording and storing Midi data with arduino and midi shield

texts: i need help getting started on writing a sketch that would let me record and store midi data from a midi controller connected to a arduino mega through a midi shield. are there any functions in the midi library that will aid in this task?


texts: Can Digital/Analogue pins double as power supplies?

texts: I'm doing research into if the Arduino Uno has enough power pin slots to power multiple components, and I'm unsure if it's possible to convert some of the pins from the Digital and Analogue sections to be power/ground. Anyone know>


texts: Differences between Arduino Uno SMD and Uno DIP

texts:
I just bought an Arduino Uno (SMD version) from W11Stop and want to know whether there is any other difference between Arduino UNO DIP and Arduino UNO SMD besides knowing that the SMD version doesn't have a DIP chip which can be replaced?

I am just a beginner so please help me if I am wrong!


texts: Serial - Send data to Arduino while Arduino sending data

texts:
Arduino send data to PC each iteration. When I'm trying to send data to Arduino while receiving data from it, it takes too long. Serial.available() returns false even I sent data from PC. But if I add delay like 20-30 ms, problem fixed. Can't I use serial simultaneously?

PS: It's Arduino mega and I'm using http://www.teuniz.net/RS-232/ library for serial communication.

Example code:

void loop(){

  if(Serial.available())
    Serial.write("goodbye", 7);
    Serial.write("hello", 5);
  }

In this situation, it takes long time to write "goodbye" after I sent data to Arduino.


texts: Is there a way to have the LED switch on after 10 readings or say a minute?

texts:
I am using Arduino for a RFID project where the LED must switch on after either 12 readings of the tag or 2 minute, the tag reading happen every 10 seconds. I can't seem to figure out a way to have the LED switch on only after the above mentioned conditions.

I have tried doing various if loop much to my failure, below is the code I am currently using:

#include <RFID.h>
#include <SPI.h>
#define SS_PIN 10
#define RST_PIN 9
#define LED_PIN A0

RFID rfid(SS_PIN, RST_PIN);
int serNum[5];
String cardno;
int interval = 15000; // millisec
long now = 0;
long lasttime = millis();
// change Reader ID to your name
String readerID = "Reader_001";

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
  pinMode(A0, OUTPUT);
}

void loop() {
  now = millis();
  if (now > lasttime + interval) {
    lasttime = now;
    Serial.print(readerID);
    Serial.print(":");
    Serial.println("I am alive");
  }
  if (rfid.isCard()) {
    if (rfid.readCardSerial()) {
      lasttime = now;
      cardno = String(rfid.serNum[0]) +
               String(rfid.serNum[1]) +
               String(rfid.serNum[2]) +
               String(rfid.serNum[3]) +
               String(rfid.serNum[4]);

      Serial.print(readerID);
      Serial.print(":");
      Serial.println(cardno);
    }
  }
  rfid.halt();
  delay(10000);
}

The expected outcome is the LED switching on after 2 minutes of contact between the tag and the reader.


texts: How to Set the Control Register on the DS3231 RTC module for Arduino UNO R3?

texts:
I am using the DS3231 RTC connected to an Arduino UNO R3 for a project. I won’t go into detail, but I need to save power, therefore I am using the DS3231 Alarm Interrupt to wake the Arduino from sleep. The Alarm Interrupt works fine when the Arduino is sleeping and connected to the 5V and GND pins of the Arduino, however it turns out that the DS3231 won’t fire a square wave interrupt when on battery power. In order to turn it on, I need to set bit 7 of the Control Register (0Eh) to logic 1, and bit 6 to logic one. I can’t find any documentation on how to do this, except for a few forums talking about it. What is the specific code to do this, and where would I place the code?

DS3231 Data Sheet (Control Register on p.13)

#include <Wire.h>
#include <RTClibExtended.h>
#include <LowPower.h>

#define wakePin 2    //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
#define ledPin 13    //use arduino on-board led for indicating sleep or wakeup status

RTC_DS3231 RTC;      //we are using the DS3231 RTC

byte AlarmFlag = 0;
byte ledStatus = 1;

//-------------------------------------------------

void wakeUp()        // here the interrupt is handled after wakeup
{
}

//------------------------------------------------------------

void setup() {
  //digitalWrite(wakePin,HIGH);
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT);

  //switch-on the on-board led for 1 second for indicating that the sketch is ok and running
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
  delay(1000);

  //Initialize communication with the clock
  Wire.begin();
  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));   //set RTC date and time to COMPILE time

  //clear any pending alarms
  RTC.armAlarm(1, false);
  RTC.clearAlarm(1);
  RTC.alarmInterrupt(1, false);
  RTC.armAlarm(2, false);
  RTC.clearAlarm(2);
  RTC.alarmInterrupt(2, false);

  //Set SQW pin to OFF (in my case it was set by default to 1Hz)
  //The output of the DS3231 INT pin is connected to this pin
  //It must be connected to Arduino D2 pin for wake-up
  RTC.writeSqwPinMode(DS3231_OFF);

  //Set alarm1 every day at 18:33
  RTC.setAlarm(ALM1_MATCH_HOURS, 16, 19, 0);   //set your wake-up time here
  RTC.alarmInterrupt(1, true);
}

//------------------------------------------------------------

void loop() {

  //On first loop we enter the sleep mode
  if (AlarmFlag == 0) {
    attachInterrupt(0, wakeUp, LOW);                       //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    digitalWrite(ledPin, LOW);                             //switch-off the led for indicating that we enter the sleep mode
    ledStatus = 0;                                         //set the led status accordingly
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);   //arduino enters sleep mode here
    detachInterrupt(0);                                    //execution resumes from here after wake-up

    //When exiting the sleep mode we clear the alarm
    RTC.armAlarm(1, false);
    RTC.clearAlarm(1);
    RTC.alarmInterrupt(1, false);
    AlarmFlag++;
  }

  //cycles the led to indicate that we are no more in sleep mode
  if (ledStatus == 0) {
    ledStatus = 1;
    digitalWrite(ledPin, HIGH);
  }
  else {
    ledStatus = 0;
    digitalWrite(ledPin, LOW);
  }

  delay(500);
}

Also, how would I set it to go to sleep after the alarm?

Thanks!

P.s sorry about that Thomas, I'm a bit new here.


texts: How do i send ads1115 data over spi to master arduino

texts:
I am trying to send ADS 1115 data which is connected with Arduino mega_1 over I2C and arduino Mega_1 is connected with arduino Mega_0 over SPI.
Arduino Mega_1 is act as a slave and send ADS 1115 data to master device..
I think my whole setup is working but i want to received actual data of ADS 1115 on master Arduino
Here is screenshots of results of my code

master

#include <SPI.h>

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

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait

void loop (void)
{
byte a;

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('a');  // add command
a=transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("results:");
  Serial.println (a);

  delay (1000);  // 1 second delay
}  // end of loop

slave

#include <Wire.h>
#include <Adafruit_ADS1015.h>
int out_buf;
int adc0;

// Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */
Adafruit_ADS1015 ads;
// what to do with incoming data
volatile byte command = 0;
void ss_falling ()
{
  command = 0;
}
void setup (void)
{
 ads.begin();
 Serial.begin(9600);
 //ads.startComparator_SingleEnded(0, 1000);
// have to send on master in, *slave out*
 pinMode(MISO, OUTPUT);

// turn on SPI in slave mode
 SPCR |= _BV(SPE);

 // turn on interrupts
 SPCR |= _BV(SPIE);
 attachInterrupt (0, ss_falling, FALLING);

}

// SPI interrupt routine
ISR (SPI_STC_vect)
{
 byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = out_buf; // add 15
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
adc0 = ads.readADC_SingleEnded(0);
Serial.print("AIN0: "); Serial.println(adc0);

out_buf=adc0;
//int buff = atoi(out_buf);
Serial.print("AIN1: "); Serial.println(out_buf);
delay(1000);
 }

i am sending 1570 but on Master side i received 35 i think ADS data is of 16 bits i.e 2 bytes and SPI received only 1 byte at a time i am stuck here please help me.
Thank you in Advance

example


texts: Using AysncUDPMessage for ESP32 to send string data

texts:
I am in search for some examples as to how can one use the AsyncUDPMessage in an Application for sending out UDP packets to a host with specific IP address and Port number from an ESP-WROOM-32 (Olimex ESP32-PoE) module?
The Class for AsyncUDPMessage in arduino-esp32 library inherits from Print.
I want to send sensor measurements to InfluxDB in the Line Protocol (InfluxDB specific).
Example
 imu,location=front,nodeid=node1 status=0.00,liac_x=-1.18,liac_y=0.02,liac_z=9.63,eul_x=0.00,eul_y=-6.81,eul_z=0.25 1538507409930

The above mentioned example is stored in the form of a String and the methods to send information via UDP viz. send() sendTo() all mention usage of AsyncUDPMessage as the first parameter.
goal
Send the above measurement to the particular Device's IP and port
udp.sendTo(Message, IPAddress(192,168,3,11), 8089);

I am currently using broadcastTo(const char * data, port) menthod to send information the InfluxDB instance.
Code
void loop(void) {

  DateTime now_time = rtc.now();

 // create a measurement
  influxMeasurement row("imu");
  row.addTag("location", "front");
  row.addTag("nodeid", "node1");

// get information from BNO055
  imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
//  Serial.print(li_ac.x());
//  Serial.print(li_ac.y());
  row.addField("status", 0);
  row.addField("liac_x", li_ac.x());
  row.addField("liac_y", li_ac.y());
  row.addField("liac_z", li_ac.z());
  row.addField("eul_x", euler.x());
  row.addField("eul_y", euler.y());
  row.addField("eul_z", euler.z());

  // add timestamp
  row.addTimeStamp_ms(String(now_time.unixtime()) + String(millis()%1000));

  // print the Line Protocol output
  Serial.println(row.postString());

  // UDP Sending
  char buf[2048]; // make buffer for `broadcastTo()`
  row.postString().toCharArray(buf, sizeof(buf)); // string to char array
  // Serial.println(buf);
  udp.broadcastTo(buf ,8089);

  delay(100);
}

method
I create a Line protocol String, make a buffer, convert the string to char [] and send it out.
Question

how do I use AsyncUDPMessage so I can pass the string to it directly?

I am not sure but will char buf[2048] within a loop is a good idea as every time a buffer allocation might make the ESP32 run out of memory? And if AsyncUDPMessage can avoid this concern?


texts:
is it possible to use a normal PNP transistor to drive a motor?
I'm kinda new to this stuff so I want to be on the safe side, so I don't damage my Arduino Uno because of the motor.

I have made a motor driver? https://circuits.io/circuits/2493784-test-1
But I'm not sure if i have done right and I wont break any components.

So does this work without any problems and have I done it right?

I'm not trying to make a H-bridge because I need both PNP and NPN?

EDIT:Picture


texts:
I'm using a timer to fire a interrupt in configurable time periods.
In that ISR, a pin is toggled, and a uint32_t variable is incremented.

In the main program, a while loop waits until that variable has reached a certain threshold - to then disable the timer via its clock source selection.

while(stepcounter <= threshold) {
}
disablecounter();

Sometimes - depending on optimization level, whether I put a small delay in the while loop, etc., this check seems to fail - advancing to disablecounter() even though stepcounter has not reached threshold.

If I stack the while loop like this:

while(stepcounter <= threshold) {
}
while(stepcounter <= threshold) {
}
disablecounter();

it runs just fine. This also works:

while(stepcounter <= threshold) {
  while(stepcounter <= threshold) {
  }
}
disablecounter();

I'm assuming there's some odd behaviour when comparing rapidly changing 32-bit numbers against a threshold.
This issue also occurs when using a uint16_t for stepcounter, but after a higher number of cycles.

For analysis, I'm simply running this loop over and over again; setting stepcounter back to 0 and restarting the timer. With uint32_t, it usually fails after the 5th or so loop. For uint16_t, it fails after around 25 loops.

Using a tempstepcounter like this also seems to work, but only when comparing against both counters at the same time:

while(tempstepcounter <= threshold || stepcounter <= threshold) {
  tempstepcounter = stepcounter;
}
disablecounter();

Any ideas on this? It this because 32-bit numbers take longer to read from the registers than the time from ISR to ISR?
ISR frequency should be around 32 kHz during this.

ISR code:

ISR(TIMER1_COMPA_vect) {
  PORTF ^= (1 << PORTF0));
  stepcounter++;
}


texts: integer overflow in expression [-Woverflow] - TinyCircuit

texts:
I have a tiny circuit Bluetooth shield and I was testing out the sample code that was provided by tinycircuit. However, when I tried uploading the sample code into the board, I kept having the following error. How can I solve this error?

this is the piece of code where there error seems to be happening.

#define  ADV_INTERVAL_MIN_MS  50
#define  ADV_INTERVAL_MAX_MS  100

void setConnectable(void)
{
  tBleStatus ret;

  const char local_name[] = {AD_TYPE_COMPLETE_LOCAL_NAME, 'B', 'l', 'u', 'e', 'N', 'R', 'G'};

  hci_le_set_scan_resp_data(0, NULL);
  PRINTF("General Discoverable Mode.\n");

  ret = aci_gap_set_discoverable(ADV_IND,
                                 (ADV_INTERVAL_MIN_MS * 1000) / 625, (ADV_INTERVAL_MAX_MS * 1000) / 625,
                                 STATIC_RANDOM_ADDR, NO_WHITE_LIST_USE,
                                 sizeof(local_name), local_name, 0, NULL, 0, 0);

  if (ret != BLE_STATUS_SUCCESS)
    PRINTF("%d\n", (uint8_t)ret);

}


texts: Compute yaw from magnetometer and accelerometer

texts:
I use an Arduino and a 9 DOF sensor (gyroscope, accelerometer and magnetometer) and I'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity.

I managed to correctly compute pitch and roll (the z and x axis in unity) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my yaw too, in a weird way.

Code in the arduino to get the heading

void getHeading(void)
{
  heading=180*atan2(Mxyz[0],Mxyz[1])/PI;
  if(heading <0) heading +=360;
}

void getTiltHeading(void)
{
  //float pitch = asin(-Axyz[0]);
  //float roll = asin(Axyz[1]/cos(pitch));
  float pitch = atan( Axyz[0] / sqrt( Axyz[1] * Axyz[1] + Axyz[2] * Axyz[2] ) );
  float roll = atan( Axyz[1] / sqrt(Axyz[0] * Axyz[0] + Axyz[2] * Axyz[2]));

  float xh = Mxyz[0] * cos(pitch) + Mxyz[2] * sin(pitch);
  float yh = Mxyz[0] * sin(roll) * sin(pitch) + Mxyz[1] * cos(roll) - Mxyz[2] * sin(roll) * cos(pitch);
  float zh = -Mxyz[0] * cos(roll) * sin(pitch) + Mxyz[1] * sin(roll) + Mxyz[2] * cos(roll) * cos(pitch);
  tiltheading = 180 * atan2(yh, xh)/PI;
  if(yh<0)    tiltheading +=360;
}

Pitch and roll

    float _Pitch  = (float)(180 / Math.PI * Math.Atan( m_ResultX / Math.Sqrt( m_ResultY * m_ResultY + m_ResultZ * m_ResultZ ) ) );
    float _Roll = (float)(180 / Math.PI * Math.Atan(m_ResultY / Math.Sqrt(m_ResultX * m_ResultX + m_ResultZ * m_ResultZ)));
    float _Yaw = (float)(m_TiltHeadingResult);

Don't hesitate to ask for details.


texts: Are INTx pins the only ones eligible for Software Serial?

texts: As opposed to PCINT (Atmel's Pin Change INTerrupt, INTx is arduino-compatible interupt)  In other words, does Software Serial use atmel's pin change or arduino falling interrupt?


texts:
can i run Atmega1284P at 3.3V and 8Mhz speed.? can i burn Nick Gammon Arduino bootloaders into the chip.?

Thank You


texts: How to 'label' module using electric techniques

texts:
I am in a project where it makes set of 'modules(set of separate circuits that will work as a sensor when connected to the board' that would be connected to Arduino Mega.

Currently, I'm planning to connect 'modules' with the Mega board using RJ-45(also known as LAN cable) cables.

At first, using voltage divider circuit, I tried to identify these 'modules' by attaching a resistor to it, so that if the board sends 5V to the 'module', it gets the resistance of the resistor inside the module.

But, as soon as I tested, this way seemed a bit unstable, because the measured resistance of the resistor kept changing.

Now, is there any other way to 'label' the module? I'm a beginner in this thing, so I'll appreciate any help that is provided.

Thanks in advance.

Ps. the voltage divider circuit that I used can be found in here:

Ps2. the resistor in the module does not mean the total resistance of the circuit in the module. It's separate.


texts: Help understanding how to drive Step motors with Arduino

texts:
I am building a 2-Axis gantry system to dispense some thermal paste on boards. I was given two stepper motors in order to do so along with a gantry already built that will arrive in two weeks. So basically I just need to figure out how to drive them on the software side. However the boss demands testable code to be finished by EOB tomorrow, despite the hardware not being here yet. So I drafted some quick code that should drive a stepper motor, it's an easy open loop system, but I'm struggling. The operator will home the gantry after each cycle so it's just a matter of getting the motors moving.

My method was as follows:

#include <Stepper.h>
*declaring the stepper and all that goes here*
void loop(){ etc.
   basic logic flow stuff
   stepper.step(20); // to move forward twenty steps
   stepper.step(-20) // to move back twenty steps

However my boss says this is incorrect as I need to be giving the steppers both step and direction.

After some tenuous google searching he recommended I use the AccelStepper library to fix this problem. After looking through this library I'm unsure how this will give me anything I need (distances are so small acceleration is useless) and how I am not giving it both step and direction in my original example code, I give it steps (20) and a direction with my negative/positive coefficient.

Am I correct in my thinking? Is there a better solution neither of us have found? I'd love to understand not just that I'm wrong, but why I am.


texts: Interface gps and ultrasonic sensor simultaneously

texts:
I am able to interface  gps and the ultrasonic sensor and obtain data successfully for individual interfacing with the Arduino UNO. When I combined the code for these two, I only get the data values from gps but no measurement values are obtained for the ultrasonic sensor.In the variable data, I have stored the gps data packet. I have read the solution for the same problem but none of them worked. I have attached the code below:

    #include <SoftwareSerial.h>
    #include "TinyGPS++.h"

    SoftwareSerial serial_connection(8, 9);

    TinyGPSPlus gps;
    TinyGPSCustom Trackingangle(gps, "GPRMC", 8);
    TinyGPSCustom Dir_NS (gps, "GPRMC", 4);
    TinyGPSCustom Dir_EW (gps, "GPRMC", 6);

    String data,tr,ew,ns,d1;
  int a=0;
    const int trigPin = 6;
    const int echoPin = 7;
    long duration;
    int distance;
    int buttonPin = 12;
    String s="",str_dist="",str_button="";
    int buttonPushCounter = 0;
    int buttonState = 0;
    int lastButtonState = 0;

    void setup()
    {
      pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(buttonPin, INPUT);
      Serial.begin(9600);
            serial_connection.begin(9600);
    }

    void loop()
    {
      data="";tr="";d1="";
    serial_connection.listen();
     dat_gps();
       if(data!="")
    {
    Serial.println("GPS DATA= "+data);
    ultra();
      }
   }
        void ultra()
    {
distance=0;duration=0;
         digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    //if(duration!=0)
    {
      distance= duration*0.034/2;
        Serial.print("Distance= ");
    Serial.println(String(distance));
    }
    }

    void dat_gps()
    {
     {
      while(serial_connection.available())
      {
        gps.encode(serial_connection.read());
      }

    if (Trackingangle.isUpdated())
    {
        tr=String(Trackingangle.value()); //    Serial.println(tr);
    }
    if (Dir_EW.isUpdated())
    {

     ew=String(Dir_EW.value());
    }
    if (Dir_NS.isUpdated())
    {

      ns=String(Dir_NS.value());
    }
    if(tr!="")
    { if(gps.location.isUpdated())
     {       delay(2000);
        data=String(gps.satellites.value());
       data+=",";
       if(data!="0,")
       {
        data+=String(gps.location.lat(), 6);
        data+=",";
        data+=String(gps.location.lng(), 6);
        data+=",";
           data+=String(gps.speed.mph());
              String a=String(gps.altitude.feet());
         if(a!="")
       {   data+=",";
       data+=a;
         data+=",";
          data+=String(gps.hdop.value());
         data+=",";
         data+=tr;
         data+=",";
         data+=ns;
         data+=",";
         data+=ew;
         data+="";
            }
       }}
      }
     }
    }


texts:
I would like to create a simple remote controller (IR) with my Arduino Nano that would control my PC. (Volume up/down, stop, play and that sort of things...)
I have no problem with creating 'hardware part' and Arduino script, that would send commands through serial as a reaction to IR signals.
I can imagine python script that would react to commands received on the serial port.

My problem is: "How can I detect on which port should I listen to?" What is the right way to do it?


texts: Send data from GSM module to cloud server like firebase

texts: I am trying to search for anything to send my sensor data from Arduino + GSM SIM900A to a cloud server, preferably firebase. Does anyone know how can I achieve this operation to firebase or any other cloud database?


texts:
So, maybe it's my understanding that is at fault or maybe it's tinkercad. It's probably the former. But anyway here's my problem

I've connected it according to picture

https://imgur.com/a/h2HYgUE

There is no power going through the anode. The cathode is going to ground.
On the upper side 5v is going to base and the emitter sends signals to an input on pin 12.

If i digitalRead pin 12 and Serial.write it. it says 1. which is weird, least for my understanding.

As i understood there needs to be power going through the anode which lights up the diode inside the optocoupler. however there is no power going through the anode yet the emitter gives off a signal.

Anyone mind helping me out in understanding why this is?

Please ignore the resistors on the image


texts:
I'm trying to use an if statement to check when the time goes past a specific point and run a specific function. To do this I'm looking to convert time into a double and running something along the lines of if(timeCurrent >= 8.30). I seem to however have an issue with the conversion part, normally I'm aware the standard practice in C++ would be to do the following:

DateTime now = rtc.now();
static char buffer[80];

sprintf(buffer, "%02d.%02d", now.hour(), now.minute());
String str(buffer);
double timeCurrent = strtod(str);

However, this doesn't work for Arduino. What can be done to create the same desired function?


texts: motor shield directly to PC? WITHOUT ARDUINO!

texts:
Is there a way to connect and control motor shield board WITHOUT Arduino at all.
can i connect it directly to my PC ?
i'm getting confused since i red lot of topics that people use existing pins on motherboard.


texts: How to make an Arduino USB programming circuit?

texts: I am designing a PCB in which I am using the MCU used in Arduino UNO which is Atmega328P and some other components as per my project requirements. I have almost designed the circuit but I am confused with the USB programming part. I want my MCU to be programmed using USB B Type just like we do it in Arduino UNO. My friend suggests me to purchase an Arduino UNO device and program that MCU and then put it in my circuit. But I don't want to do it like this. I have found the schematic design but its very confusing. Can anyone help me out with this.?


texts: How to save a state - make an arduino run a code only once/make aruduino bahave differently the next time he is on

texts:
Im building a arduino based bicycle speedometer. When the code starts the user picks his bike size (which I need to calculate the radius). Then I have a state finite machine where the user taps the button between speed, time and temperature. I need to put this circuit on a battery and it needs to be mounted on a bike. But every time you plug and unplug the battery, the code runs from the beginning again, which I don't want. So every time the user turns the speedometer off then on, he needs to pick his bike size again. Is it possible to save the size he has picked so that the next time he turns it on, it doesn't come across.
So - user has his speedometer, turns it on, picks the bike size, turns it off, then sometime later turns it back on and the part for picking the bike size doesn't show up, it simply "knows" remembers what the user picked last time.
I don't know how could that work, would the Arduino run the certain code only once or is there a function for "the next time Arduino has electricity behave like this".


texts: My Arduino Ethernet shield is not working

texts:
Actually I'm using a W5100 Hanrun HR911105A 16/02 Ethernet shield with an Arduino Uno (original).

I tried this code from the examples:

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

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};
IPAddress ip(192, 168, 1, 177);
IPAddress myDns(192,168,1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
// telnet defaults to port 23
EthernetServer server(23);
boolean gotAMessage = false;
// whether or not you got a message from the client yet

void setup() {
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // start the Ethernet connection:
  Serial.println("Trying to get an IP address using DHCP");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // initialize the Ethernet device not using DHCP:
    Ethernet.begin(mac, ip, myDns, gateway, subnet);
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  ip = Ethernet.localIP();
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(ip[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
  // start listening for clients
  server.begin();
}

void loop() {
  // wait for a new client:
  EthernetClient client = server.available();
  // when the client sends the first byte, say hello:
  if (client) {
    if (!gotAMessage) {
      Serial.println("We have a new client");
      client.println("Hello, client!");
      gotAMessage = true;
    }
    // read the bytes incoming from the client:
    char thisChar = client.read();
    // echo the bytes back to the client:
    server.write(thisChar);
    // echo the bytes to the server as well:
    Serial.print(thisChar);
    Ethernet.maintain();
  }
}

That code prints the following on the serial monitor:

Trying to get an IP address using DHCP
Failed to configure Ethernet using DHCP
My IP address: 192.168.1.177.

So what is the problem? Why it is not connecting? I tried all the ethernet examples, but not one works. I don't know, maybe the problem is that I don't have a sticker of MAC address on the shield and I'm using the MAC address of the examples. Or maybe I'm writing the IP address wrong? Here is the data from the network connection details.

Connection-specific DNS Suffix: zte.com.cn
Description: Intel(R) Dual Band Wireless-AC 3165
Physical Address: 72-57-C5-BC-66-07
DHCP Enabled: Yes
IPv4 Address: 192.168.1.2
IPv4 Subnet Mask: 255.255.255.0
IPv4 Default Gateway: 192.168.1.1
IPv4 DHCP Server: 192.168.1.1
IPv4 DNS Server: 192.168.1.1
IPv4 WINS Server:
NetBIOS over Tcpip Enabled: Yes
Link-local IPv6 Address: fe80::b523:b9f2:b43c:6a8a%14
IPv6 Default Gateway:
IPv6 DNS Server:

My router is a ZTE model ZXHNH108N.


texts: Arduino ESP8266 direct/fast control of the digital pins

texts: How does one control a digital pin directly avoiding the slow digitalWrite or digitalRead?


texts: When I connect the Arduino to my PC the Led "ON" lights for a second then turns OFF. I wonder if the Arduino has a fault?


texts: Is it possible to connect many (20+) SPI sensors to an Arduino Mega?

texts:
I am making a system for measuring whether or not there is vacuum present in big steel containers. They are located up to 100 meters from the control cabinet.

The question is, how many SPI sensors can I successfully use at the same time with an Arduino Mega?

I have two main concerns, and there are probably more things I didn't think about.

Signal strength
The shared lines for CLK, MOSI and MISO will need to be split up at several junction boxes and led to the different sensors. Since the voltage out from the Arduino is fixed, I'm fearing instability because the signal is weaker for some sensors, has someone done something similar? What is the greatest acceptable voltage loss for these lines to an ordinary sensor?

Processing
Will the SPI library be fine coping with this many sensors?

The refresh rate can be set to extremely low, thinking 0.3Hz.

The alternative to all this is to go for 4-20mA sensors and have a 0-5V converter circuit for each sensor, near the controller.

Any inputs would be greatly appreciated!


texts:
Objective: interface and Arduino MEGA to a Mettler Toledo SB32001 using the RS-232 communication protocol described in the manual.

Equipment Used:

SB32001 Mettler Toledo 32 kg scale
Arduino MEGA
Sparkfun RS232 Shifter - SMD

Background:

I am using the SoftwareSerial library to try to communicate with the scale through MEGA pins 52 and 53. I have the level shifter connected to the scale using a through cable.

So far, I have tried to send the most basic command to the scale, and the command is both not executing, and not causing a status code to be send back (i.e. failure OR success). My Tx light on the level shifter flashes, but the Rx light never does.

Write string to screen:

D "String"

Because I have a through cable, I have tried switching the Tx and Rx pins in code. Neither has worked.

The from the scale has the following options I can set:

Baud Rate: 150, 300, 600, 1200, 2400, 4800, 9600
Parity: 7b-E, 7b-no, 8b-no, 7b-odd

Here is a minimal (non)working example of my code:

#include <SoftwareSerial.h>

const int pinTX = 53;
const int pinRX = 52;

scale = SoftwareSerial(53, 52);

void setup(){
    Serial.begin(9600);
    scale.begin(9600);
    delay(100);
}

void loop(){
    scale.println("D \"Hello!?\"");
    delay(100);

    while (scale.available()){
        Serial.print(scale.read());
    }
    Serial.println()
    delay(100);
}

What I need:

I need help figuring out where I should look next to solve this issue. I have tried switching the transmit and receive pins in software. I have tried using jumpers to switch the Tx and Rx pins in hardware. I have tried 7 and 8-bit settings with no parity. Nothing give me a signal back. Totally perplexed?

Is it my converter chip? Does anyone know of problems with this shifter? I know that it does not contain the industry standard MAX232


texts:
I need to know how I can write integer values in EEPROM and retain the value on power on.

char *Red = strstr(myTestUrl, "/R");
if (Red) {
  int RedValue  = atoi(Red + 2);
  analogWrite(12, RedValue);
  Serial.println("Red :");
  Serial.println(RedValue);
}

I want to write RedValue in EEPROM. How can it be done?


texts: Necessary torque of motor to move a door.

texts: I am building an automatic door opener and for its mechanism I need a motor with a high torque and low speed. My question here is how to measure the torque needed to move the door as I cannot really weigh the door and find its mass. Can anyone help me out?


texts: How to define and use a list/array of chars using `Serial.print`

texts:
I wish to define a list of months names and access it when printing a report.

Array was defined as follows:

const char months []=
{'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'};

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

                                 Serial.print(months[i]);
                        }

Tries:

I was looking for help under Arrays in Arduino documentation didn't give, as far as I found, any explanation for such case, but arrays of int

Appreciate any help.


texts: 4-digit 7-segment display resets when common pin set to HIGH

texts:
I'm trying to make a simple stopwatch application with my Arduino Mega 2560 and a 4-digit 7-segment display, but the leftmost three digits only light up for a split second before they go out every time the counter increments up. The rightmost digit is counting normally.

After going back to basics to diagnose the problem, I've discovered that every time one of the common pins is set back to high so I can pick another digit to manipulate, the digit goes blank.

Code for my basic program, which should display "0123" on my display.

int A = 2;
int B = 3;
int C = 4;
int D = 5;
int E = 6;
int f = 7;
int G = 8;
int P = 9;

int D4 = 10;
int D3 = 11;
int D2 = 12;
int D1 = 13;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(P, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //0
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //1
  digitalWrite(A, LOW);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, LOW);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, LOW);
  digitalWrite(D4, HIGH);
  delay(5);

  //2
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, LOW);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, LOW);
  delay(5);

  //3
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

}

void loop() {
}

But all the display shows is a 3 on the rightmost digit. I followed the video in this guide and hooked my Mega up the same way. Is this still the right way to code a 4 digit display to make all the digits display different numbers, or is this normal behavior?


texts: Which input pins can I use on the ESP8266 NodeMCU

texts:
On the ESP8266 NodeMCU I have GPIO2 , GPIO3 , GPIO1 , GPIO9 free but when I assign them to a button they do not work. I assume it is because those pins have other function behind them. When I look at the schematic I found that they are TXD1, RXD0, TXD0, and SSD2. Is there a way to still use these pins as inputs?

If not, can I use an Arduino Uno for my inputs and send signals from there to the analog pin to my ESP8266 NodeMCU for the connection to the MQTT server?

For the record all my other pins are used so I can't use any other input pin than these 4.


texts: Pin headers too long for the sensor i bought

texts:
https://www.amazon.co.uk/Adafruit-TCS34725-Color-Sensor-Filter/dp/B00OKCRU5M/ref=sr_1_3?keywords=adafruit+rgb+sensor&qid=1559653098&s=computers&sr=1-3

Just bought this colour sensor for a project and as you can see it comes with the pins detached. There are 8 pins but only 7 holes so how do i assemble it? I'm assuming its super obvious since i havent seen anyone else ask it so im sorry!
Thanks in advance.


texts:
I am currently working on reading pressure values using a tekscan a201 sensor. The sensors I have are limited to 25lbs.

My plan is to use eight on these sensors of them with a arduino Mega. Since I am measuring the resistance, I am thinking of making a 8 similar voltage divider circuits and grabbing the voltage reading via arduinos analog pins.

At the moment, I am not sure how to convert these readings to engineering units. Any ideas?


texts:
Does anybody know if the following MIDI DIN connectors will fit in a breadboard?

(or in general with 'generic' electrical components?)

MIDI DIN

And the same for:

Diodes to be used for MIDI in.


texts: Turn off the second builtin Nodemcu 0.9 led

texts:
I'm making a low energy consumption device so I'd like to turn off all the led when I'm idle.

Unfortunately the nodemcu turn on a blue led while I'm idle (during delay(ms))

Here is my code:

#define LED    16

void setup() {
  initialSetup();
  //Turn off the built-in led
  digitalWrite(LED, HIGH);
}

void loop() {
  //Here I do everything
  doStuff();
  //GO TO SLEEP
  delay(3600000);
}

The led that turn on during delay is the one near to D0 pin.

The led that I can control and so turn off (pin #16 -> D0) is near the 5v pin.

It's possible to completely turn off all led to consume less?


texts: Can I add my Wi-Fi credentials to ESP module remotely?

texts:
I am working on Home automation project and I am stuck somewhere on connecting my smart switch board to internet through my home WIFI. Actually I want to connect my ESP module with my home Wi-Fi remotely.
I was think of something like creating a hotspot through my switch board and connecting the hotspot to my phone, after that I need to send my Wi-Fi credential through that hotspot from my phone to  to ESP. But I dont know actually how to implement it. I didn't find something similar like that so I came here.
If you guys have some different way or you know how to do it , then give me some information about it.


texts: Is it better to use #define or const int for constants?

texts:
Arduino is an odd hybrid, where some C++ functionality is used in the embedded world—traditionally a C environment. Indeed, a lot of Arduino code is very C like though.

C has traditionally used #defines for constants. There are a number of reasons for this:

You can't set array sizes using const int.
You can't use const int as case statement labels (though this does work in some compilers)
You can't initialize a const with another const.

You can check this question on StackOverflow for more reasoning.

So, what should we use for Arduino? I tend towards #define, but I see some code using const and some using a blend.


texts: Controlling an MCP41HV31 Digital Potentiometer

texts:
I need to control a 10kOhm digital potentiometer in rheostat mode in 256 steps. I found an Arduino tutorial, which works with an MCP41010 (I added a viper resistance according to the datasheet). This works fine - I can send values from 0 to 255 to the CS pin an the resistance between output pin A and B changes from 0 to 10kOhm.
The problem is, that my application requires 16V to go through this resistance, which the MCP41010 can't handle.

I tried to go with a MCP41HVX1 high voltage digital potentiometer (which I soldered on a TSSOP-to-DIP Breakout board) and assumed it would work the same way. Turns out it doesn't... My connections are:

Arduino nano -> MCP41HVX1

10 -> CS
11 -> SDI
13 -> SCK
5V -> VL
GND -> DGND

With the MCP41010 I connect a 115Ohm viper resistor between output pin A and wiper terminal and measure resistance between output pin A and B (pink connectors). I noticed, that the MCP41HVX1 has a different description for the rheostat modus but I can't get that to work either.

This is my circuit that works with the MCP41010

And here is the respective code (which sets the MCP41010 to 255 i.e. 10kOhm)

#include <SPI.h>
byte address = 0x11;
int CS= 10;

void setup()
{
  pinMode (CS, OUTPUT);
  SPI.begin();
}

void loop()
{
  digitalPotWrite(255, CS);

}

int digitalPotWrite(int value, char Port)
{
  digitalWrite(Port, LOW);
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(Port, HIGH);
}

Has anyone ever done this or has a clue what's going on?


texts:
I've got an Arduino faithfully monitoring our sewer lift pump. It talks to the world over Ethernet (with PoE). I'm wondering if there is any way to load new code over the Ethernet as well. Any ideas if this could be done?

I imagine that using the boot loader might be out of the question, but perhaps it would be possible to upload a new system image – perhaps onto an SD card – and then use a modified boot loader to discover the new image and copy it into place.


texts: Can a WiFi enabled Arduino make a HTTPS request to my Web Server?

texts:
I need my Arduino to connect to my web server through HTTPS, can the Arduino handle it?

It only has to act as a client.


texts:
If I use 9, 10, 7, 6 , 8, 11 pins for accelstepper, ESP8266 wont boot
If I use other pins, all good.

What is the problem?

I use accelstepper and Arduino latest versions.

sketch which won't boot -

    #include <AccelStepper.h>
#include <MultiStepper.h>

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

const char* ssid = "wiflya";
const char* password = ".........";

#define HALFSTEP 8

// Определение пинов для управления двигателем
#define motorPin1  13 // IN1 на 1-м драйвере ULN2003
#define motorPin2  12 // IN2 на 1-м драйвере ULN2003
#define motorPin3  14 // IN3 на 1-м драйвере ULN2003
#define motorPin4  16 // IN4 на 1-м драйвере ULN2003

// Определение пинов для управления двигателем
#define motor2Pin1  6 // IN1 на 2-м драйвере ULN2003
#define motor2Pin2  3 // IN2 на 2-м драйвере ULN2003
#define motor2Pin3  5 // IN3 на 2-м драйвере ULN2003
#define motor2Pin4  4 // IN4 на 2-м драйвере ULN2003

// Инициализируемся с последовательностью выводов IN1-IN3-IN2-IN4
// для использования AccelStepper с 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
AccelStepper stepper2(HALFSTEP, motor2Pin1, motor2Pin3, motor2Pin2, motor2Pin4);

void setup() {
  //Serial.begin(115200);
  //Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    //Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  stepper1.setMaxSpeed(1300.0);
  stepper1.setAcceleration(400.0);
  stepper1.setSpeed(1300.0);

  stepper2.setMaxSpeed(1300.0);
  stepper2.setAcceleration(400.0);
  stepper2.setSpeed(1300.0);

  //stepper1.moveTo(20000);

  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  // ArduinoOTA.setHostname("myesp8266");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.begin();
}

void loop() {
    // Изменяем направление, если шаговик достигает заданного положения
  //if(stepper1.distanceToGo()==0)
  //  stepper1.moveTo(-stepper1.currentPosition());
  stepper2.runSpeed();
  stepper1.runSpeed();
  //stepper2.runSpeed();

  ArduinoOTA.handle();
}


texts:
I have completed the circuit and code to interface ESP8266 module with Arduino UNO.

When i send AT,AT+RST from serial monitor the reply is correct .

But when i send AT commands to search WIFI networks (AT+CWLAP) & connect to WIFI (AT+CWJAP="SSID","password") the reply is ERROR.

But the IP address (may be default) is obtained as 192.168.4.1
 when i send AT+CIFSR .

Here is my code

#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3

void setup()
{
    Serial.begin(9600);
    esp8266.begin(9600); // your esp's baud rate might be different
}

void loop()
{
    if(esp8266.available()) // check if the esp is sending a message
    {
        while(esp8266.available())
        {
            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            Serial.write(c);
        }
    }
    if(Serial.available())
    {
        // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
        // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
        // but we want to send everything at the same time.
        delay(1000);
        String command="";
        while(Serial.available()) // read the command character by character
        {
            // read one character
            command+=(char)Serial.read();
        }
        esp8266.println(command); // send the read character to the esp8266
    }
}


texts: Reading Serial String Gives Null Lines with JSSC

texts:
I need to send serial data to my Arduino UNO from within a java application. I am using JSSC for this.
I wanted to verify that my data actually arrives correctly to the arduino before going to the next step of my application. For this I tried to just return the string I am sending, however when I send "test", this is what is returned:
t
null
est

I am wondering if this is a problem on the Java side with sending/reading the string, or that it's a problem with sending/reading on the arduino, and how I could possibly fix this.
This is my java code to read the data:
try {
    port.addEventListener(event -> {
        try {
            System.out.println(port.readString());
        } catch (SerialPortException e) {
            e.printStackTrace();
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}

This is my java code to send the data:
try {
    port.writeString("test");
} catch (SerialPortException e) {
    e.printStackTrace();
}

And this is the code on my arduino:
void loop() {
  while (Serial.available() > 0) {
    Serial.print(Serial.readString());
  }
}

I hope someone can help :)


texts: problem on implementation of the ultrasonic circuitry

texts:
I used an Arduino Uno on my project to produce a frequency greater than 35000Hz and the output of digital pin was connected to the ultrasonic transmitter circuitry:

However, it's not working on the transmitting side. Here's the Arduino code:

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

void loop()
{
    pinMode(13,OUTPUT);
    pinMode(12,OUTPUT);
    int pirSenses = analogRead(A1);
    int pirOuts=11;
    pinMode(pirOuts,INPUT); /*PIR sensor 1*/
    int pirSense = analogRead(A0);
    int pirOut = 10;
    pinMode(pirOut,INPUT); /*PIR sensor 2*/
    Serial.println(pirSense);Serial.println(pirSenses);

    if (pirOut || pirOuts == HIGH)
    { /*tone produces ultrasonic frequency*/
        delay(8000);
        tone(13, 50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else if (pirOut||pirOuts==LOW)
    {
        tone(13, 50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else
    {}
}

And the transmitter (model "MCPCT-G5100-4139") specification:

Please help me with this problem. Thanks!


texts: Can't get the right values with the pulse sensor and the LM35 temperature sensor . Reading 2 anolog sesnors

texts:
I am trying to combine the two sensors (pulse sensor using this library and LM35 temp)(on a Arduino UNO board),but there is a problem with them when is a noise at the pulse sensor .The values are fluctuates especially the LM35 it goes from 31 degrees (normal value ) to 25-50 and even the pulse one changes .

Here are the results .

The code is this(I got the code form the  Getting_BPM_to_Monitor sketch ) :

#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

const int sensor = A5; // Assigning analog pin A5 to variable ‘sensor’
float tempc; //variable to store temperature in degree Celsius
float vout; //temporary variable to hold sensor reading
//  Variables
const int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
// Otherwise leave the default "550" value.

PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"
void setup() {
  Serial.begin(9600);          // For Serial Monitor
  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);
  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }
}

void loop() {
  int temp = analogTemp();
  Serial.print(temp);
  Serial.println("Temp");

  if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
    // Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
    int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
    // "myBPM" hold this BPM value now.
    Serial.print("BPM: ");                        // Print phrase "BPM: "
    Serial.print(myBPM);                        // Print the value inside of myBPM.
    Serial.println(" A HeartBeat Happened ! ");
  }
  delay(20);                    // considered best practice in a simple sketch.
}
float analogTemp() {
  vout = analogRead(sensor);
  vout = (vout * 500) / 1023;
  return vout; // Storing value in Degree Celsius

}


texts:
Though I've written C/C++ code for a long time, the unseen limitations on how memory was consumed on various MCU and SOC programming platforms have often tripped me up. As I'm about to build up code for my first large project for my NANO boards, which will likely use a fair amount of its resources, I'd like to be better prepared for any surprising and unexpected "gotchas" to look out for.

For example, on another SOC I recently worked on extensively (The Pololu.com wixel) I was very surprised to learn that function/method arguments and auto variables, which I'd normally expect to be stack allocated and recovered when a function returns were in fact permanently allocated for the life of the program! Wow! so on that platform, where I'd normally hate to "overwork" variables or reuse variables after their names no longer make sense, I had to adjust my coding to what I'd normally consider BAD for readability. Not to mention realizing that simple loop variables were better off allocated globally. Yecch!

Can those of you who have run into such unexpected coding issues in the Arduino environment share some "special" guidelines about things like this?


texts: How do I make a stepper motor compass cross 360° to 0°?

texts:
I am building a wet compass for a flight simulator. I currently have a stepper motor functioning well with the simulator but at the point of crossing 360° to 0° the stepper does a full reverse 360° to get into position.

My question... can anyone please assist me in creating code that makes the linear cross from 360° to 0° work in both directions?

The simulator feeds a float val that is a degree out of 360° e.g. 172.13. My stepper has 4076 steps per full revolution. You will see the math in the code below. I am using the AccelStepper library.

void ProgOut(byte id, float val) {
switch (1) {
case 1:

if (val)
        { stepper1.moveTo(val * 11.3222222);         }

        stepper1.run();

break; }}

I have tried something like this:

void ProgOut(byte id, float val) {
switch (1) {
case 1:
if ( stepper1.distanceToGo () >= 4064){
          stepper1.moveTo(4076);
          stepper1.setCurrentPosition(0);
}
    else if (val)
        {

                stepper1.moveTo(val * 11.3222222);
        }

        stepper1.run();

break; }}


texts: Is there a way to "list" (in BASIC, or "cat" in LINUX) the current sketch loaded in my xxxDUINO?

texts: I was surprised when I couldn't find an old post where someone asked this question. Seems like a natural beginner, uh excuse me, "newbie" question, but then I'm a throw-back to the days when a home computer came with 3,583 bytes (three-thousand, five-hundred eighty-three). So again, as seen in the title, can I "list" my sketch? I'm pretty sure the answer is NO since if it were a good question someone would have asked it already. It just strikes me as odd that my old VIC-20 could do something this phenomenal techno-marvel can't. Not much of an accomplishment for the dinosaurs, but HEY! We're on the scoreboard now! [nothing's worse than that miserable goose-egg :(   ]


texts: Read all relay output (high or low) from Bluetooth through Android app

texts:
I have written the following code for Arduino:

#define relay2 2
#define relay3 3
#define relay4 4
#define relay5 5
#define relay6 6
#define relay7 7
#define relay8 8
#define relay9 9
byte val;
void setup() {
  Serial.begin(9600);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  pinMode(relay5, OUTPUT);
  pinMode(relay6, OUTPUT);
  pinMode(relay7, OUTPUT);
  pinMode(relay8, OUTPUT);
}

void loop() {
  int a = 0;
  if (Serial.available()) {
    val = Serial.read();
    Serial.println(int(val));
    //Display received value on Serial Monitor
    //ASCII VALUES
    if (int(val) == 49) //Turn Light1 ON 1
      digitalWrite(relay2, HIGH);
    else if (int(val) == 50) //Turn Light1 OFF 2
      digitalWrite(relay2, LOW);
    if (int(val) == 51) //Turn Light2 ON
      digitalWrite(relay3, HIGH);
    else if (int(val) == 52) //Turn Light2 OFF
      digitalWrite(relay3, LOW);
    if (int(val) == 53) //Turn Light3 ON
      digitalWrite(relay4, HIGH);
    else if (int(val) == 54) //Turn Light3 OFF
      digitalWrite(relay4, LOW);
    if (int(val) == 55) //Turn AC ON
      digitalWrite(relay5, HIGH);
    else if (int(val) == 56) //Turn AC OFF
      digitalWrite(relay5, LOW);
    if (int(val) == 57) //Lock the DOOR
      digitalWrite(relay6, HIGH);
    else if (int(val) == 48) //Unlock the DOOR
      digitalWrite(relay6, LOW);
  }
}

Now on the Android side I have written the following code:

 //Bluetooth connection code ....
  mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

  mmSocket.connect();
  mmOutputStream = mmSocket.getOutputStream();
  mmInputStream = mmSocket.getInputStream();

  int byteCount = mmInputStream.available();
  if (byteCount > 0) {
    byte[] rawBytes = new byte[byteCount];
    mmInputStream.read(rawBytes);
    String string = new String(rawBytes);
    Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
  }

Now it works perfectly when I press a button to turn the light on/off. But I want to read all relay current status (high/low) when a Bluetooth connection is made.

So basically after connecting to the Bluetooth module I want all relay status.

How can I do that?


texts: How can I reference an object from another file?

texts:
I am trying to write some code to make it easy to add different buttons to a touch screen. I need each object to be a different object of class 'touchButton'. I'd like to be able to run a touchButton.Draw function, which in turn will run LCD library commands. Is there a way I could do that? Here is my source code:

TouchScreen.ino:

#include "touchButton.h"
#include <UTFT.h>
#include <UTouch.h>
#include <avr/pgmspace.h>
UTFT    myGLCD(ITDB32S, 38, 39, 40, 41);
UTouch  myTouch( 6, 5, 4, 3, 2);
extern uint8_t SmallFont[];

void setup() {
  myGLCD.InitLCD();
  myGLCD.setFont(SmallFont);
  myGLCD.clrScr();
  myTouch.InitTouch();
  myTouch.setPrecision(PREC_MEDIUM);
  myGLCD.fillScr(51, 51, 51);
  //what I want to be able to do:
  //touchButton Button1 (10, 10, 20, 20, 'p');
  //Button1.Draw();
}

void loop() {
}

touchButton.h

#ifndef touchButton_h
#define touchButton_h
#include "Arduino.h"
class touchButton {
  public:
    touchButton(int x, int y, int xs, int ys, char use);
    void Draw();
    int x1;
    int y1;
    int xsize;
    int ysize;
    char use;
    boolean toggle = false;
};
#endif

touchButton.cpp

  #include "Arduino.h"
  #include "touchButton.h"
  touchButton::touchButton(int x, int y, int xs, int ys, char myuse) {
    x1 = x;
    y1 = y;
    xsize = xs;
    ysize = ys;
    use = myuse;
  }

  void touchButton::Draw() {
    switch (use) {
      case 'p':
      //this is what I would like to have called from the main file.
      //myGLCD.drawRoundRect(x1, y1, x1+xsize, y1+ysize);
        break;

       default:
        break;
    }
  }


texts: How to use sparkfun qwiic rfid with arduino uno

texts:
https://learn.sparkfun.com/tutorials/sparkfun-qwiic-rfid-idxxla-hookup-guide

Hardware:
Arduino UNO R3
Sparkfun qwiic rfid
Id-20LA

I followed this tutorial. I used the code on the website. I don't have a qwiic wire so i used standard i2c.

VCC->3.3V
GND->GND
SDA->A4
SCL->A5
INT->8

I ran it and nothing happens. I removed the if in the loop function to see if that is the problem and it just shows rfid 00000 so it must not be reading. Also i can see the arduino and sparkfun boards pwr led on. The read led on the sparkfun never blinks. I don't know where to look.

Also, unrelated question. If i wanted to read with this setup and after that add a bluetooth send the id tag via bluetooth on an android app. Both bluetooth and rfid would be on software serial. I saw that uno supports only 1 serial at a time. My question. Should i get an arduino Mega?

If something is unclear feel free to ask me.


texts: Control solenoid valve with arduino running on battery

texts:
I built a simple setup according to this tutorial using a 9v battery (in the meantime replaced it with a 120A battery):
https://www.bc-robotics.com/tutorials/controlling-a-solenoid-valve-with-arduino/

Also i attached a humiditiy sensor to measure the soil-humidity.
My plan is:
2 times a day (evening and morning before sunrise) wake up arduino and check humidity, if it is below a certain %, open the 12v-valve, wich i operate at 9v (like the one in the tutorial).

I read a lot about how to reduce power on the arduino and found this tutorial for the pro mini, wich seems a LOT easier than to modify the standard arduino uno:
https://www.whizzy.org/2015/06/howto-very-low-power-usage-on-pro-mini-v2-arduino-clone/

Now, my question is:
would a pro mini v2 work as well for controlling the valve? On the uno, i have the vin-pin wich provides the 9v for the valve, on the pro mini instead, as far as i understood, i need to use that pin (named RAW pin there) as power supply for the arduino... but how would i get out the 9v from the arduino like i did on the uno? Is there any possibility at all?

Thanks in advance!


texts:
All the other examples I've seen have had coding errors where they set a pin LOW in a loop with no delay so that it goes high again right away - but this problem is different, and probably something obvious.

I set up a breadboard memory (EEPROM or similarly-pinned flash) programmer (ala BenEater and many similar sources) using two 74**595s for the first 15 address bits as well as the OE# bit in the MSB spot, and the nano digital outputs for the 8 data bits as well as the WE# (write-enable) bit.  The data, address, and OE# pins set correctly every time.  The WE# pin, however, stays HIGH forever once it goes HIGH.

I have tried every digital pin for WE#, I have tried every analog pin with an analogWrite.  I have tried now three different memory chips and three Arduino Nanos that I've used successfully elsewhere, but still no success.

The only thing I can assume is that the WE# pin on the memory ICs somehow is keeping the line high, but I can't for the life of me figure out how that's possible.

Code and logic analyzer example:

/*
 EEPROM Programmer
 In this case, programming a SST39SF010A
 55ns read access, 22us write time
 Software Data Protection to write:
 (0x5555, 0xAA)
 (0x2AAA, 0x55)
 (0x5555, 0xA0)
 */

#define SHIFT_DATA  13
#define SHIFT_CLK   12
#define SHIFT_LATCH 11
#define ROM_D0      2
#define ROM_D1      3
#define ROM_D2      4
#define ROM_D3      5
#define ROM_D4      6
#define ROM_D5      7
#define ROM_D6      8
#define ROM_D7      9
#define WRITE_EN    10

void setAddress(int address, bool outputEnable) {
  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, ((address >> 8) | (outputEnable ? 0x00 : 0x80))); // High bits
  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, address); // Low bits
  digitalWrite(SHIFT_LATCH, LOW);
  digitalWrite(SHIFT_LATCH, HIGH);
  digitalWrite(SHIFT_LATCH, LOW);
}

byte readROM(int address) {
  for (int pin = ROM_D0; pin <= ROM_D7; pin++) {
    pinMode(pin, INPUT);
  }
  byte data = 0;
  setAddress(address, /* outputEnable */ true);
  // Read each pin
  for (int pin = ROM_D7; pin >= ROM_D0; pin--) {
    data = (data << 1) + digitalRead(pin);
  }
  return data;
}

void printContents() {
  for (int base = 0; base < 256; base += 16) {
    byte data[16];
    char buf[80];
    for (int offset = 0; offset < 16; offset++) {
      data[offset] = readROM(base + offset);
    }
    // buffer (string) to hold the formatted data
    sprintf(buf, "%03x:  %02x %02x %02x %02x %02x %02x %02x %02x  %02x %02x %02x %02x %02x %02x %02x %02x",
      base, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
      data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]);
    Serial.println(buf);
  }
}

void writeROM(int address, byte data) {
  for (int pin = ROM_D0; pin <= ROM_D7; pin++) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
  }
  setAddress(address, /* outputEnable */ false);
  for (int pin = ROM_D0; pin <= ROM_D7; pin++) {
    digitalWrite(pin, (data & 0x01));
    data = (data >> 1);
  }
  digitalWrite(10, LOW);
  delayMicroseconds(10);
  digitalWrite(10, HIGH);
  delay(1);
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(56700);
  Serial.flush();

  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);

  // Set pull-up resistor
  digitalWrite(WRITE_EN, HIGH);
  pinMode(WRITE_EN, OUTPUT);

  Serial.println();

  writeROM(0x5555, 0xAA);
  writeROM(0x2AAA, 0x55);
  writeROM(0x5555, 0xA0);
  for (int i = 0; i < 256; i++)
  {
    writeROM(i, i % 13);
  }
  printContents();
}

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


texts: My ESP8266 web server is only displaying text, even after ensuring content type is text/HTML

texts:
So I just got my two ESP8266/ESP-12E WiFi development boards in the mail as I am trying to set up a few home automation devices in my house. I've gotten much further than I thought I would today, considering this is my first foray into working with circuits that involve microprocessors/WiFi, but I've run into a problem that I can't find a solution to myself.  Forgive me if there is another question similar to this, but I could not find it and this seems like the best place to ask.

I am using a tutorial/template program that Rui Santos from Random Nerd Tutorials was kind enough to create ( https://randomnerdtutorials.com/esp8266-web-server/ ), and although we have (as far as I can tell) identical boards, operating systems and Arduino code, I keep getting an HTML page that is text only, with none of the CSS or HTML elements showing.  It should look like this:

However, I am getting a page that looks like this:

His serial monitor is giving this response:

My serial monitor is giving me this response:

I've tried putting client.println("Content-type:text/html"); in a few places to see if it would help display the page, but to no avail.  Any help with getting this little program/website running would be greatly appreciated.

Thanks for your time!


texts:
I have a fistful of Pro Mini clones with atmega168 ICs. Oddly they have 16MHz crystals. When I feed it nominal 3.7V (really 4V, but it will spend most time around 3.7) via the RAW pin, I see 2.6V on VCC and RST pins. Of course I’d like a bit more for my MOSFETs - what’s the cause of this? It’s a 1.4V drop, is this common for pro minis?

I can feed 3.3V to VCC with a regulator, but the 16MHz crystal is puzzling. Clocked for 16MHz?


texts: I'm trying to use the MCP4725 DAC from Adafruit (https://www.adafruit.com/product/935) to output some waveforms over a frequency range up to about 50kHz. At the moment, I'm simply sending values to the DAC via the Wire library and through the DAC's onboard library. It appears that the values are only being sent at 7kHz. Is this due to the added weight of the libraries I'm using? Is there some way I can increase the transmission speed?


texts: How to create a serial communication connection between Cubieboard running Android and Arduino

texts:
I am connecting my Arduino to my Cubieboard that is running Android.

I tested this originally with my android tablet and USB cable. This worked successfully for the most part using the firmata kit but I don't want to use firmata.

I want a basic function library written in Java for use with Unity (eg Library Tutorial Video) to connect to the Arduino via the USB serial port connection much like a connection with my Windows computer.

I'd like basic command functions like:

Connect / Open
Write
Read
Flush
Close

I was thinking maybe of using this library here but I am unsure how to go about this. I know similar discussion have already taken place on the forum claiming it may not be possible, but it is very clear that it is. It has been done many times. All I need to do is send strings with serial after finding the Arduino's COM port and reading from the serial.


texts:
I'm converting a 0-5v PWM signal to an analog signal using an LM358D. I've connected the output to an oscilloscope to look at the signal but I'm not really sure what I'm looking at. The PWM looks ok but I'm unsure of the analog signal.
Here's some images, please let me know what you think.
Both pics are at 50% signal strength. The oscilloscope is set to defaults, simply connected the probe.
Thanks

EDIT:
Here's the schematic for the PWM to analog converter. The cap is a tantalum. The dip switch changes the analog from 5v to 10v, the signal looks the same on both and is correct voltage so seems to be ok?


texts:
I am trying to write a code where photoresistors (a or b) sense blinking of the light, and lights LED (k and d) simultaneosly with that blinking. And I want that when both photoresistors sense dark for more than 3 secs, the LEDs would light up and stay until one of them again gets lighting. But I cannot understand in which part should I put millis time count?

int k = 2;
int d = 3;
int fk = A0;
int fd = A1;
int a = 0;
int b = 0;

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

void loop()
{
  a = analogRead (fk);
  b = analogRead (fd);
  while (a < 1000 && b < 1000)
  {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    a = analogRead (fk);
    b = analogRead (fd);
  }
  if (a > 1000)
    digitalWrite(2, HIGH);
  else
    digitalWrite(2, LOW);
  if (b > 1000)
    digitalWrite(3, HIGH);
  else
    digitalWrite(3, LOW);
}


texts: SoftSerial freezes on comparing getInt to int

texts:
I have a robot application on my Arduino which basically takes values from a SoftSerial instance on my 0/1 pins (connected to a Bluetooth board).

From the 'driver station' I send speed values to the Arduino through the aforementioned Bluetooth controller. The freezing happens when I compare the data (an integer) to a local integer (i.e 500). If I send the reverse command, I'm actually sending the int 500. If I compare my SoftSerial data like so:

if(softSerial.parseInt() == 500)
{
 //Reverse
}else{
 //Forward
}

it freezes. It only happens when I'm using my SoftSerial stack over Bluetooth, over USB it doesn't freeze. What are my options?