texts: Mega pin stuck high after driving optocoupler

texts:
I have an Arduino Mega which is driving a board. On the board is a quad optocoupler (K847PH). Pins 42 - 45 of the Arduino are each attached to the Anode of a opto. The cathode goes to ground through a 50ohm resistor. I've used multiple boards and have had no issues with this part of the circuitry so far. I recently attached a new board (same circuit) and began testing. I noticed I had ~1.1V on pin 1 of the opto (Anode). After some debugging I checked the voltage coming out of the Arduino to that pin (42 on the Mega) and noticed it was 5V. I ran a new sketch to drive and hold the voltage low but the voltage remains at 5V.

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

void loop() {
  digitalWrite(42, LOW);
}

Looking at the schematic of the Mega it appears pin 42 is directly connected to the ATMEGA1280-16AU. Is there anything I can do to fix the Mega? Should I just replace the ATMEGA1280-16AU? Is there something I can probe to check? It does appear there is > 1Mohm of isolation between pin 42 and the 5V rail.


texts: 'MeDCMotor' does not name a type error inside mBlock

texts:
I was using a 3rd party programming enviroment, mBlock 3.4.5 for making C++ Arduino programmes with a graphical programming language. I was compiling a program and the following eroor came up.

project_Untitled0_0.ino:65:1: error: 'MeDCMotor' does not name a type
project_Untitled0_0.ino:66:1: error: 'MeDCMotor' does not name a type
project_Untitled0_0.ino: In function 'void move(int, int)':
project_Untitled0_0.ino:85:7: error: 'motor_9' was not declared in this scope
project_Untitled0_0.ino:85:24: error: 'M1' was not declared in this scope
project_Untitled0_0.ino:86:7: error: 'motor_10' was not declared in this scope
'MeDCMotor' does not name a type

I took another look at the program and there were some lines of code that seem they are added in the program by deafult:

MeDCMotor motor_9(9);
MeDCMotor motor_10(10);
void move(int direction, int speed)
{
      int leftSpeed = 0;
      int rightSpeed = 0;
      if(direction == 1){
            leftSpeed = speed;
            rightSpeed = speed;
      }else if(direction == 2){
            leftSpeed = -speed;
            rightSpeed = -speed;
      }else if(direction == 3){
            leftSpeed = -speed;
            rightSpeed = speed;
      }else if(direction == 4){
            leftSpeed = speed;
            rightSpeed = -speed;
      }
      motor_9.run((9)==M1?-(leftSpeed):(leftSpeed));
      motor_10.run((10)==M1?-(rightSpeed):(rightSpeed));
}

Since the program does not recognise the MeDCMotor class the program failed to upload.

I am running Windows 10 home edition on a 64-bit laptop.

Is there a way to remove the lines of code that prevent me from uploading the sketch or are there other ways to solve it?


texts:
I wrote a simple program for controlling an LED using mobile. So, I bought the HC-05 bluetooth module configured it and then connected it to  the arduino.

This is the code that I wrote for it.

int ledPin1=13;
int state;
int flag=0;

void setup()
{
    pinMode(ledPin1, OUTPUT);
    digitalWrite(0,HIGH);

    second:
    Serial.begin(9600);
}

void loop()
{
    if(Serial.available() >0)
    {
        state = Serial.read();
        flag=0;
    }
    if (state == '0')
    {
        digitalWrite(ledPin1, LOW);
        if(flag == 0){
            Serial.println("led off");
            flag=1;
        }
    }
    if (state == '1')
    {
        digitalWrite(ledPin1, HIGH);
        if(flag == 0){
            Serial.println("led on");
            flag=1;
        }
    }
}

Everything is working cool with the serial monitor. But, I'm not able to control it using my mobile. I gave an input 1 in serial monitor and if showed "led on". the same thing appears on the commanding interface of the app used in the mobile. So, the bluetooth is transmitting information from the arduino to mobile but I'm not able to send commands from the mobile and control the led. I tried using various apps like  Blueterm, Ardudroid etc but, the situation remains the same.

What am I doing wrong? Is there something wrong with the code?

I'm using Arduino Uno.


texts:
I wrote Arduino sketch and it works. It waits for a command and answers text on response.

Simultaneously, I can't get any response with command line tools.

For example, I have the following code to get temperature:

#!/bin/bash
tty=/dev/ttyUSB0
exec 4<$tty 5>$tty
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
#stty -F $tty 9600 -echo
#printf "temp\n" >&5
echo temp >&5
read reply <&4
echo "$reply"
#tail -n 1 - <&4

It returns empty or hang under different circumstances.

Also, if I run built-in Serial Monitor, I can see responses on command lines like:

echo temp > /dev/ttyUSB0

But I see nothing with commands like tail -f /dev/ttyUSB0

What I am doing wrong?


texts:
I'd like to build a simple GPS system. It should be very little. For the software side, I will build an API, so from my PC/smartphone/whatever else I could ask the GPS system where it is located (I think Google provides this kind of feature).

How can I do this? My main problem is the GPS and the its building. I'd like to build the smallest thing possible, because I have to hide it. My idea is to hide this GPS system in my bike: I'd like to locate my bike if someone stole it. As you can see, internet is a problem.

I'm not asking to design anything. I would only know what I need to build a basic GPS system that has just the feature described. What do I need? Is it possible to do it? Does GPS require Internet connection? I would know if I could make it or not without internet access.


texts: Is there any good way to calibrate the watchdog timer? I'm trying to use it as a time source, even when asleep, but it's woefully inaccurate. Some simple testing showed it loosing 2 minutes every hour!


texts: expected primary expression before ')' token

texts:
#define ANALOG_IN 0

void setup() {

  Serial.begin(19200);

  analogReference(INTERNAL);

}

void loop() {

  int val = analogRead(ANALOG_IN);

  Serial.print(0xff, byte);

  Serial.print( (val >> 8) & 0xff, byte);

  Serial.print( val & 0xff, byte);

}

This is my code and I'm getting this error for all 3 Serial.print commands. Please help.


texts: How important is the INT pin of the MPU6050 (GY-521)?

texts:
I want to wire multiple MPU6050 (at least 16 of them) to an arduino UNO for development (then nano for production). So I first started wiring one MPU6050 to an arduino like shown on the diyhacking website or in the picture below:

as you can see in the picture above the INT pin is used.
I then wearched for a way to wire multiple MPU6050 to an arduino using a multiplexer and I found a way on horizonlab's website or see the picture below:

As you can see in the second picture the INT isn't used at all. I'd like to know how important it is and what I'm missing out by not using it.


texts: Best practices for really long distance sensor deployments

texts:
I'm noob to Arduino and electronics, but here is a problem from life which I need to solve for myself:

We grow strawberries and early spring freezes can take most of the flowers from the plants. One way to protect this is to have some kind of heating in solar houses, but if you grow outside, your best option is to watering the flowers on the crops when the freezing comes.

I want to deploy at least 3-4 temperature sensors, which are placed at every parts of the land, which will send the data for an Arduino which will turn on the pump with a relay (for this part I also want to use a pre-built relay solution with socket plugs already built, I don't want to mess around with high electricity myself).

For a cable solution (like catKIT system) I need at least 100m cable for the farest part of the land, which can be managable, but later on, scaling the land lots of cables everywhere can be a problem.

So the best solution would be if every temperature sensor is a standalone station, data transmitted by wireless to the main Arduino which is triggering the pump. This way there will be lass cables on the land, less change to cable break by tractor, etc.

Also, with a wireless system, I don't have to deal with signal loss over the cable, just only wireless signal loss. Is it possible to correct this by middle wireless signal transmitter stations? Or even better, all of them connected to each other!?

Like if the farest sensor reading Celsius 0.8, middle sensor reading Celsius 1.2. Middle sensor have a variable to also consider any reading from the farest sensor, which is reading 0.8. If that reading under Celsius 1, than don't bother his own output, send 0.8 to the main Arduino which is triggering the pump.

These station's power input still need to be solved, but maybe solar panels can be an option? However I have a clue that night they will not work, most of them freezing comes at night.

I saw wireless shields for arduino which offering even a km range in ideal conditions. But how degrading when the conditions are not ideal, like a house wall, rain, fog, snow?

Is it possible to feed multiple wireless inputs too one arduino? 3-4-10-20 standalone stations which transmitting temperature reads for the main arduino. If one of them sends lower temperature than +1 Celsius, than the pump will be turned on. Is it possible to solve this?

Thank You for your answers!


texts: Does toCharArray prevent a String being created on the heap?

texts:
I know it's bad to use Strings due to the memory problems that can occur.
I've tried to remove all instances of strings from my code.
But I'm not sure about this line:

http.getString().toCharArray(ipAddressBuffer, lengthOfIPAddress);

Is calling toCharArray() enough to prevent memory problems? Or is there a string still being created on the heap?

If it's still created on the heap, how can I modify the code so it only deals with cstrings?

Here's my code:

void setIPAddress(char* ipAddressBuffer){
  HTTPClient http;
  http.begin("http://bot.whatismyipaddress.com/"); //Only allowed to call once per 5 mins.
  http.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
  int httpCode = http.GET();
  if (httpCode > 0) {
    http.getString().toCharArray(ipAddressBuffer, lengthOfIPAddress);
  }
  else {
    Serial.println("Error on HTTP request");
  }
  http.end();
}

I'm using the HTTPClient.h library btw.


texts: Arduino program wont work properly for some reason

texts:
I have a arduino program that I wrote with my teammembers. We are working on a project and try to move a RC car. Here is our code.

int forward =12 ; //assign to correlating pin attached to TP06
int backward = 11; //assign to correlating pin attached to TP07
int left = 10; //assign to correlating pin attached to (left steer)
int right = 9; //assign to correlating pin attached to (right steer)

// TP09 & TP02 (don't remember which is left and right)

void setup() {
pinMode(forward, OUTPUT);
pinMode(backward, OUTPUT);
pinMode(left, OUTPUT);
pinMode(right, OUTPUT);
}

void move_Forward() {
digitalWrite(forward, HIGH);
digitalWrite(backward, LOW);
}

void move_Backward() {
digitalWrite(backward, HIGH);
digitalWrite(forward, LOW);
}

void turn_Left() {
digitalWrite(left, HIGH);
digitalWrite(right, LOW);
}

void turn_Right() {
digitalWrite(right, HIGH);
digitalWrite(left, LOW);
}

void stop_Completely() {
digitalWrite(forward, LOW);
digitalWrite(backward, LOW);
digitalWrite(right, LOW);
digitalWrite(left, LOW);
}

// loop will keep going while arduino has power
void loop() {
move_Forward();
turn_Left();
}

When we run this code, for some reason forward pin and left pins are becoming deactivated, which are the pin numbers 12 and 10. Like it does not supply voltage anymore for some reason. However right pin and backward pins, which are pins 9 and 11, which was not included in loop, works! I can run the RC car with these pins. I dont understand why this is the case. Shouldn't the left and forward pins work? If they are not working, how come? Sorry I am new to arduino programming language and its been very challenging for me and my group. Thanks in advance.


texts:
So the task is to control 12v DC motor.
With first button, you can add up motor speed by certain speed step.
With second button, you can slow down motors speed by certain speed step.
With third button you cant speed up motor to its max, but problem is there that i must be done smoothly. For example i press third button and in motor starts to spin faster and faster till it reaches max speed. But now when i press this button motor jumps to it max, and i don't know why. There is no smoothness.
I cant use delay, must be done by millis
[code]
int speed = 0;
int motor = 5,
    fasterbutton = 7, slowerrbutton = 4, tillmaxbutton = 2;
unsigned long previousMillis = 0;
const long interval = 100;
const long smoothinterval = 5000;
boolean faster, slower, tillend;
int begginingspeed;
const int step = 3;
const int maxspeed = 255;

void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, OUTPUT);
  pinMode(7, INPUT_PULLUP);
  Serial.begin(9600);
}
void loop() {
  tillend = digitalRead(2);
  slower = digitalRead(4);
  faster = digitalRead(7);

  //button Nr 7 start DC motor and festens up
  if (faster == !HIGH && begginingspeed < maxspeed) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      begginingspeed += step;
      if (faster == !HIGH && speed < 1 ) {
        Serial.print('\n');
        Serial.print("MOTOR ON" );
      }
      analogWrite(motor, begginingspeed);
      Serial.print('\n');
      Serial.print("Speed = " );
      speed = begginingspeed * 100 / maxspeed;
      Serial.print(speed, DEC);
      previousMillis = currentMillis;
    }
  }

  //button Nr 4 slows down  DC motor
  else if (slower == !HIGH && begginingspeed > 0) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      begginingspeed -= step;
      analogWrite(motor, begginingspeed);
      Serial.print('\n');
      Serial.print("Speed = " );
      speed = begginingspeed * 100 / maxspeed;
      Serial.print(speed, DEC);
      if (slower == !HIGH && speed < 1 ) {
        Serial.print('\n');
        Serial.print("MOTOR OFF" );
      }
      previousMillis = currentMillis;
    }
  }

  //button Nr 2 for smooth fastens up DC motor till max
  if (tillend == !HIGH && begginingspeed > 0) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis <= interval) {
      for (begginingspeed = begginingspeed; begginingspeed <= 255; begginingspeed += step)
        analogWrite(motor, begginingspeed);
    }
    previousMillis = currentMillis;
  }

}
[/code]


texts: Converting 8 bit binary to a hexadecimal pair as unsigned char

texts:
I have a function:
void Epd::SendData(unsigned char data) {
  digitalWrite(dc_pin, HIGH);
  SpiTransfer(data);
}

At the moment I am hardcoding data sent to it by calculating on paper and then writing the result as code, but I want to improve that. For example, I am calling:
SendData(0x03);
SendData(0x1f);

To get those two values (0x03 and 0x1f) I am converting the decimal value of 799 to binary: 1100011111 and then adding 0 at the beginning to make sure my binary result is 16 digits long: 0000 0011 0001 1111. After that, I convert every 4 bits to hexadecimal value and sending them as pairs using the SendData function.
I feel like I am almost there, but I don't know how to convert my result to proper type in order to send it to the SendData function:
void Epd::SendDecAsData(int dec) {
  int binary[16];
  for (int i = 0; i < 16; i++) {
    binary[i] = dec % 2;
    dec = dec / 2;
  }

  int dec1 = binary[15] * 8 + binary[14] * 4 + binary[13] * 2 + binary[12];
  int dec2 = binary[11] * 8 + binary[10] * 4 + binary[9] * 2 + binary[8];
  int dec3 = binary[7] * 8 + binary[6] * 4 + binary[5] * 2 + binary[4];
  int dec4 = binary[3] * 8 + binary[2] * 4 + binary[1] * 2 + binary[0];

  String val1 = "0x" + String(dec1, HEX) + String(dec2, HEX);
  String val2 = "0x" + String(dec3, HEX) + String(dec4, HEX);

  SendData(val1); // error because I'm sending `String` instead of `unsigned char`
  SendData(val2);
}

I need help converting those strings (val1, val2) to the right data type, or even better, optimizing this process to get the final result in the right type with less code/computation (probably avoiding conversion to String).


texts: Errors occured when switching from Uno to Nano Every

texts:
I wrote a code that worked perfectly on an Uno. I switched everything out to a Nano Every, and now I'm getting the following errors:
In file included from C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal\src\LiquidCrystal.cpp:1:0:

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal\src\LiquidCrystal.h:45:36: error: expected class-name before '{' token
 class LiquidCrystal : public Print {
                                    ^
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal\src\LiquidCrystal.h:86:9: error: 'Print' has not been declared
   using Print::write;
         ^~~~~

exit status 1

Error compiling for board Arduino Nano Every.

I'm new to programming (this is the first thing I've done that wasn't from a tutorial), so I don't understand what any of the above means.
In the Tools dropdown, I have
Board: Arduino Nano Every
Registers Emulation: None (ATMEGA4809)
Programmer: Onboard Atmel mEDBG (Uno Wifi Rev2)
Here's the code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
  lcd.print("Charging");
  delay(750);
  lcd.print(".");
  delay(750);
  lcd.print(".");
  delay(750);
  lcd.print(".");
  delay(750);
  lcd.clear();
  lcd.print("Charged");
}

void loop() {
  const int buzzerPin = 6;
  const int switchPin = 13;
  const int buttonPin = 7;
  const int ledPin = 9;
  pinMode(switchPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  int switchState = digitalRead(switchPin);
  int buttonState = digitalRead(buttonPin);
  lcd.setCursor(0, 1);
  lcd.print("Mode: ");
  if (switchState == LOW) {
    lcd.print("Stun");
  } else {
    lcd.print("Kill");
  }
  if (buttonState == HIGH) {
    const int buzzerMax = 2000;
    const int time = 3;
    int buzzerTone;
    int totalReps = 50;
    int reps = 10;
    while (reps < totalReps) {
      buzzerTone = ((totalReps - reps) * 2 * (buzzerMax / totalReps));
      tone(buzzerPin, buzzerTone);
      analogWrite(ledPin, (255 / reps));
      delay(time);
      reps++;
      delay(time);
      if (reps == totalReps) {
        noTone(buzzerPin);
        analogWrite(ledPin, 0);
      }
    }
    lcd.clear();
    lcd.print("Charging");
    delay(333);
    lcd.print(".");
    delay(333);
    lcd.print(".");
    delay(333);
    lcd.print(".");
    delay(333);
    lcd.clear();
    lcd.print("Charged");
  }
}


texts:
I am using i2cdev library

Code:(i did not know this code is correct or not)

#include <Arduino.h>
#include <MPU6050.h>
#include <kalman.h>
#include <stdint.h>

#define ACCELLSB  2048
#define GYROLSB   16.4

#define CONSOLE
#define CALIBRATE

#ifdef  CALIBRATE
int16_t Accel_X_offset;
int16_t Accel_Y_offset;
int16_t Accel_Z_offset;

int16_t Gyro_X_offset;
int16_t Gyro_Y_offset;
int16_t Gyro_Z_offset;
#endif

MPU6050 mpu6050;

Kalman  AngleX;
Kalman  AngleY;

void setup()
{
   mpu6050.initialize();
   mpu6050.setFullScaleAccelRange(MPU6050_ACCEL_FS_16);
   mpu6050.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

   #ifdef CALIBRATE
   mpu6050.CalibrateAccel();
   mpu6050.CalibrateGyro();

   Accel_X_offset = mpu6050.getXAccelOffset();
   Accel_Y_offset = mpu6050.getYAccelOffset();
   Accel_Z_offset = mpu6050.getZAccelOffset();

   Gyro_X_offset  = mpu6050.getXGyroOffset();
   Gyro_Y_offset  = mpu6050.getYGyroOffset();
   Gyro_Z_offset  = mpu6050.getZGyroOffset();
   #endif

   int16_t AccelX, AccelY, AccelZ;
   int16_t GyroX, GyroY, GyroZ;

   mpu6050.getMotion6(&AccelX,&AccelY,&AccelZ,&GyroX,&GyroY,&GyroZ);

   // I am going to use this values in kalman filter
   #ifdef CALIBRATE
   AccelX -= Accel_X_offset;
   AccelY -= Accel_Y_offset;
   AccelZ -= Accel_Z_offset;

   GyroX  -= Gyro_X_offset;
   GyroY  -= Gyro_Y_offset;
   GyroZ  -= Gyro_Z_offset;
   #endif
}

void loop()
{

}

What is the correct way to calibrate mpu6050(Correct me what i am wrong or this is correct)?

Thanks.


texts: How do I read numbers from a serial sequence

texts:
I have read through a number of posts including How do I split an incoming string? However I cannot work out how to extract numbers from a serial string.

My challenge is this;

I send a serial command 'freq\r' to a radio which will return a string like this 'FREQ: 10138.7 RX, INHIBIT TX'. The only thing I want out of this is the 1013 so I can then manipulate it and send out a second serial port. It sounds easy enough but I just don't seem to be able to extract those numbers easily because I don't have a separator to use.

The other thing is if the number is below 10 e.g. 9138 I only want to extract the first 3 numbers then add a leading 0 so I end up with 0913.

Once I have the four numbers I can then divide them so I end up with e.g. 09 and 13 or 10 and 13. I can then send these as HEX to my second serial device.

If you are wondering what the numbers are they are frequencies in kHz which I am extracting from a radio then converting to HEX to tune a pre-selector.

Any help would be greatly appreciated as this is my last stumbling block on this serial translator project. I hope this makes sense.

Thanks

Callum


texts:
I'm trying to test my analog signal before I send it to an actual analog device. I've written some code and considering the analog square I have expected to see a digital ON or OFF during a single duty cycle but I'm either seeing all OFF for analog values 0-127 and all ON for values 128-255.

My expectation is that I would see 51 ON and 49 OFF thus getting a value closer to 128 of 255.

What am I missing? Is this even possible?

int OUTPUT_PIN = 2; // digital 2 (PWM)
int INPUT_PIN = A0; // analog 0

void setup() {
  pinMode(OUTPUT_PIN, OUTPUT);
  pinMode(INPUT_PIN, INPUT);

  Serial.begin(9600);
}

void loop() {

  analogWrite(OUTPUT_PIN, 128);

  float j = 0;
  for(int i = 0; i < 100; ++i) { // get 100 reads per duty cycle
    float v;
    v = digitalRead( INPUT_PIN );
    if(v >= 1) Serial.println("ON");
    if(v <= 0) Serial.println("OFF");
    j += v;

    delay(12); // trying to match the duty cycle
  }
  j /= 100; // average out the 100 reads

  Serial.println(j);

}


texts: Get hour with ctime (time library with ESP8266)

texts:
#include <ESP8266WiFi.h>
#include <time.h>

const char* ssid = "";
const char* password = "";
int timezone = 3;
int dst = 0;

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("\nConnecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
  Serial.println("\nWaiting for time");
  while (!time(nullptr)) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
}

void loop() {
  time_t now = time(nullptr);
  Serial.println(ctime(&now));
  delay(1000);
}

This is my code, but it shows the time like this: Sun Jul 23 15:21:12 2017. But what I want it to do is to only show the current hour, not everything.
Is it possible to do that?


texts: Can you fry an arduino with nothing plugged in to it?

texts: I only get to work on my arduino every few weeks, so sometimes and get interrupted a lot by small children, so if I completely forget what is on the firmware, then I unplug the pins (because I haven't got anything soldered on there) should I be 100% certain I'm not going to fry my board?


texts: LED staying on after first relay trigger

texts:
I seem to have a strange issue with a simple circuit involving a relay.

The problem is that the relay appears to work absolutely fine (judging from the onboard led) but the the led stays on after the first pull up on the relay.

It doesn't turn off and match the onboard relay led. I'm sure it's something minor but I can't seem to spot the problem.

I've attached a video and the code below. Thanks in advance

video

#include <Arduino.h>
int Relay = 3;

void setup()
{
  pinMode(Relay, OUTPUT);     //Set Pin3 as output
}
void loop()
{
          digitalWrite(Relay, HIGH);   //Turn off relay
          delay(2000);
          digitalWrite(Relay, LOW);    //Turn on relay
          delay(2000);
}


texts: One free pin. Need to display output for the user?

texts:
I'm working with lightblue bean. I have a device that writes data to an SD card on a long button press and switches what will be written (from a list of 5 items) on short button press.

The output, printed both to the SD card and to serial looks like this:

12:38, 7/15/15, subway
12:55, 7/15/15, subway
12:38, 7/15/15, bus
12:55, 7/15/15, rail

etc. It's basically a time stamp then a vale from this list:

char* modes[]= {"walking", "subway", "bus", "railroad", "other"};

This works perfectly. But the bean has very few pins:

5 SCK  -- connected to SD card.
4 MISO -- connected to SD card.
3 MOSI -- connected to SD card.
2 SS   -- connected to SD card.
1      -- input button, takes long and short presses
0      --
A1 SDA --- connected to real time clock for timestamp
A0 SCL --- connected to RTC (real time clock) for timestamp

I have one free DIGITAL pin. I need to let the user know what they have selected. This could be done with 5 LEDs that light up next to the user's choice, or maybe displayed text? This is a portable item so a servo that points to the user's choice might be too unreliable.

I've done some research into shift registers. They all seem to need 3 digital pins min. If I could do it with 2 I could rework the button...

Ideas?


texts: Sound quality is poor using a piezo in TinkerCad

texts:
I did a quick search and couldn't seem to find this question posted already, but I'm sure it must have so forgive me if it's a repeat.

I'm using a piezo and Arduino on TinkerCad to produce notes using the tone function, and the quality is not great (it's as if I can hear beats while the note is playing). I vaguely remember a colleague telling me this was an issue with the way my computer speakers handle square waves (I have a Macbook Air if that makes any difference), but I'm not positive. Has anyone had success in using TinkerCad to produce nicer sounding notes? If not, can anyone explain what the issue is to me?

Thank you!


texts:
I am making a device which can multiply the analog input signal with respect to the selected gain from the digital inputs. Here I have used two digital inputs(from which I can have four selections) but I am planing to add two inputs more(then I can have 16 selections). I made the code with if else statements is there any shorter way to do that? or else the code is getting huge.

here is the code:

#define sensor A0
#define resetPin 3
#define measurePin 2
#define k1 3
#define k2 4

float A = 0;
float J = 0;
int resetstatus = 0;
int measurestatus = 0;

void setup() {
  Serial.begin(9600);
  pinMode(sensor,INPUT);
  pinMode(resetPin,INPUT_PULLUP);
  pinMode(measurePin,INPUT_PULLUP);
  pinMode(k1,INPUT_PULLUP);
  pinMode(k2,INPUT_PULLUP);
  Serial.println("INITIALAIZING");
  delay(3000);
  Serial.println("Ready to begin");
  delay(200);
  }

void loop()
{
  resetstatus = digitalRead(resetPin);
  measurestatus = digitalRead(measurePin);
  if(resetstatus == LOW)
  {
    reset();
    delay(200);
  }
  if(measurestatus == LOW)
  {
    if(digitalRead(k1 == LOW) && digitalRead(k2 == LOW))
    {
    J = 1.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1 == LOW) && digitalRead(k2 == HIGH))
    {
    J = 2.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1 == HIGH) && digitalRead(k2 == LOW))
    {
    J = 3.0;
    measure();
    delay(50);
    }
    if(digitalRead(k1 == HIGH) && digitalRead(k2 == HIGH))
    {
    J = 4.0;
    measure();
    delay(50);
    }
  }
}
void measure()
{
  A = analogRead(sensor);
  float sumA = A * J;
  Serial.println(sumA);
}
void reset()
{
  Serial.println("reset");
}

I am having a problem with the output from this code
(I am using a potentiometer to feed the arduino an analog value)

I dont know why the output is showing 993 and 3972 at each cycle. can someone explain?


texts: Is there any way to add Inverse Text color function into SSD1306Ascii library like which is available in ssd1306 adafruit library ?


texts: Charge 14500 LiFePO4 lithium batteries from an Arduino Nano

texts:
I've recently started tinkering with Arduino, and I'm attempting to build a little 2WD robot based on an Arduino Nano.

I was thinking of powering the robot using two 14500 LiFePO4 batteries, which I understand will fit in a standard 2 x AA battery holder, and in series will give me about 6.4V, which should be ideal.

If I were instead going to use AA batteries, I think I'd need 4 of them, which will make my robot a fair bit bulkier.

I would like to be able to charge the batteries simply by plugging a standard USB cable into the Nano's USB socket.

Is there some easy way to safely do this? Do I need a separate charging module board, or is there some way to do it directly from the Nano?


texts: Serial throughput using AltSoftSerial on Arduino

texts:
My project involves a commercially available device that can be remotely controlled by a computer over RS232. I'd like to put an Arduino Pro Mini, which has a second serial port provided by the AltSoftSerial Library, between the device and the computer. One of the Arduino's serial ports will connect to the device under control, and the other will connect to the computer. One function of the Arduino will be to simply read incoming data on one port and immediately write it to the other port. I'm not yet sure how heavy the serial traffic will be, although my early impression is that it will come from sporadic, user-initiated commands and resulting responses.

Assuming all baud, stop bit, data bits and parity are configured correctly, is what I'm proposing possible with the AltSoftSerial Library? Is it likely that this approach will introduce delays and/or errors that are prohibitive?


texts: Enabling keyboard feature on Arduino with CH340G

texts: I've seen here that it is possible to enable keyboard feature on Arduino Uno so it can emulate a keyboard (send keystrokes to computer) like the Leonardo. They do it by updating ATmega16U2 firmware. But I bought a cheap arduino clone that uses CH340G instead of this chip. Is there any way to do the same with this chip? Can this even work on standard arduino uno?


texts: Two ints declared simultaneously, one "does not name a type"

texts:
I have several integers, all of which are declared and set to zero in setup. However, in a method, I can only modify the value of half of those integers. The method is to read several buttons and return which of them have been pressed (precondition is that no more than one buttons are pressed):

  int readButtons(){
  rbuttonState = digitalRead(right);
  lbuttonState = digitalRead(left);
  sbuttonState = digitalRead(sel);
  obuttonState = digitalRead(off);
  nbuttonState = digitalRead(snooze);
  int ret = -1;
  if (rbuttonState != lastrButtonState){
        if (rbuttonState == HIGH) {
            ret = right;
          }
        }
        if (lbuttonState != lastlButtonState){
          if (lbuttonState == HIGH) {
            ret = left;
          }
        }
        if (sbuttonState != lastsButtonState){
          if (sbuttonState == HIGH) {
            ret = sel;
          }
        }
        if (obuttonState != lastoButtonState){
          if (obuttonState == HIGH) {
            ret = off;
          }
        }
        if (nbuttonState != lastnButtonState){
          if (nbuttonState == HIGH) {
            ret = snooze;
          }
        }
  }
  lastrButtonState = rbuttonState;
  lastlButtonState = lbuttonState;
  lastsButtonState = sbuttonState;
  lastoButtonState = obuttonState;
  lastnButtonState = nbuttonState;
  return ret;
}

Yet I have the errors that

Arduino: 1.6.12 (Mac OS X), Board: "Arduino Nano, ATmega328"

Nixie_Clock_0:65: error: 'lastrButtonState' does not name a type
   lastrButtonState = rbuttonState;
   ^
Nixie_Clock_0:66: error: 'lastlButtonState' does not name a type
   lastlButtonState = lbuttonState;
   ^
Nixie_Clock_0:67: error: 'lastsButtonState' does not name a type
   lastsButtonState = sbuttonState;
   ^
Nixie_Clock_0:68: error: 'lastoButtonState' does not name a type
   lastoButtonState = obuttonState;
   ^
Nixie_Clock_0:69: error: 'lastnButtonState' does not name a type
   lastnButtonState = nbuttonState;
   ^
Nixie_Clock_0:70: error: expected unqualified-id before 'return'
   return ret;
   ^
Nixie_Clock_0:71: error: expected declaration before '}' token
 }
 ^
exit status 1
'lastrButtonState' does not name a type

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

(The last line of code is line 72).
I am at a complete loss. Any help?


texts: How to accept user input (array, variables,...)

texts:
I am working on a project using my Arduino mega2560 that triggers a solenoid (maximum of three solenoids), my camera and my flash (maximum of two flashes). The core routine is there, and working.

Now I want to refine this by adding a menu and 16x2 LCD with 6 buttons (up/down/left/right/select/reset). This is meant to be so the user can change the default values for:
- the amount of solenoids to be used (max 3),
- the amount of drops per solenoid (max 3),
- the time between drops and
- the time between active solenoids.
The layout of the menu is there, but not yet coded.

My default values for solenoids used, droplet size, droplet timing, solenoid timing, camera delay and flash(es) delay(s) are put in an array. Through the menu the default values will be presented to the user. He can accept (select button) or change the value within certain limits using the up/down buttons.

The question is, what is an easy (for a beginner like me) to program way to accept user input and store this in the array, overwriting the presented default value? I also would like to have the possibility for the user to back out of a menu option and leave the default setting of the specific submenu value.

I was thinking of creating a shadow array with blanks, to be filled in by the user and copy all the values to the array that will be used by the core routine. Another line of thinking leads me to just abandoning the array and making use of a bunch of variables. As you will probably see, I need some advice here.

Thanks very much for reading and your advice, happy to answer questions that may help clarify the issue.

Regards, Kiezel


texts:
I just cannot connect or send AT command from my UNO to A7 AI Thinker module. This is the connection:

UNO    ->    A7
TX     ->    RX
RX     ->    TX
USB    ||    5V    -> External Power Supply
GND    ->    GND

Without any sketch, I tried to send AT command from serial monitor, and nothing happened.

Different case if I use USB TTL to A7

USB TTL   ->   A7
VCC (5v)  ->   5V
GND       ->   GND
TX        ->   RX
RX        ->   TX

Then it is OK, I can send all AT command, SMS, Call, etc from the serial monitor.

Just what is happening with UNO? Does my UNO RX TX Faulty? How to check it?


texts: While Loop does not stop when condition is false

texts:
Here's the code:

void loop() {
  while (1 == 1) {
    ObsLeft();
    while (SeeLeft < 50 || SeeLeft == 50) {
      Urong();
      ObsLeft();
      if (SeeLeft > 50) {
        Hinto;
        break;
      }
    }
  }
}

ObsLeft() analogReads the Infrared sensor input and Serial.prints it

Urong() makes the sumobot go backward

Hinto() stops the robot

SeeLeft is the analog value given by the Line Sensor (in my experience, white is 42, black is 800+)

The Problem:

When I run the program with the sensor seeing White, it makes the robot go backward, but when I move the bot so that the sensor sees Black, it still keeps going.

When I run the program with the sensor seeing Black, it does nothing.


texts: Every so often ESP8266 hangs... WifiClient seems to be at fault

texts:
This code works fine without any freezes:

#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  /*if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }*/

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

While this code (with the wificlient bit commented out) freezes every so often:

#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

Only difference is in the working one the WifiClient bit of code is commented out.   How would WifiClient cause this problem?


texts:
I am using an Arduino Uno and a Mac and trying to upload my code into the board.
I tried uploading the program from different computers(MacBook Air and Pro) and I still have this problem.
How do I fix this? I tried downloading the FTDI driver. I went to the website that they suggested and tried following the instructions. I even followed other posts in Stack Exchange but I still cannot upload the code.
EDIT
Programmer -> AVRISP mkll
I am using a cable to connect to my Mac and I am using the Arduino software. The cable connected between the Arduino USB and Mac USB port.
I tried quitting and relaunching Arduino app. Once it launches I just press the upload button while my USB is plugged in. My available ports in the app are /dev/cu.Bluetooth-Incoming-Port and /dev/cu.Bluetooth-Modem
And this is the error
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device


texts:
I'm trying to connect my Arduino Uno to an ESP-01 module, but I can't get it to start correctly. All I can get out from the ESP-01 is an "invalid" message when it is enabled. Can anyone please help? Additional information can be found below.

Here's my configuration:

Arduino connected to a computer via USB cable (serial connection working)
ESP-01 connected to the same UART connection, TX from Arduino is lowered to 3,3V with resistors
ESP-01 powered with external battery + capacitor to ensure sufficient current
I've tried all different configurations with GPIO0 and GPIO2 connecting them to ground and 3,3V, with and without resistors.
I've tried 3 different ESP modules

Here's how things work:

Arduino sends back every received UART transmission so that I can monitor the whole thing.
I can send messages to Arduino from a terminal on the PC and Arduino responds.
I can send messages from Arduino by pressing a button and the messages can be seen on the terminal.
When I send AT\r\n from Arduino I can read it on the terminal but nothing happens on the ESP-01.
When I send exactly the same message from the terminal, the blue light on ESP flashes but there is no response from the ESP. Arduino sends that message back to terminal of course.
When I connect CH_PD to 3,3V the ESP gives a message: Ai-Thinker Technology Co. Ltd.
invalid
The baud rate is correct (115200) since I can only read that invalid message on this rate


texts: serialEvent only read 63Bytes and this is not the complete data incoming

texts:
hi everybody im working in a software for a pcb based in the chip ATmega2560
im use this with Xbee in API MODE, so im driving short string data and long string data.
with the short data i dont have any problem but my long data is of 78bytes.

so the serial event only show me 63 bytes and i dont find reason for it.

this is the complete block:

void serialEvent2(){
while (Serial2.available()){
    frameReceived[n] = Serial2.read();
    Serial.print("  ");
    Serial.print(frameReceived[n], HEX);
    n++;
    //Serial.print("\t" + String(n));
   /* if (n == (frameReceived[1]+frameReceived[2]) + 4){
        Serial.println();
        Serial.println((frameReceived[1]+frameReceived[2])+4);
        Serial.println("IF");
    }*/
    if ( n == 3 ){
        lfr = frameReceived[2] + 4;
    }

    if (n == lfr){
        receivedDone = true;
        Serial.println();
        Serial.print("[INFO] N: ");
        Serial.println(n);
        Serial.print("[INFO] LFR: ");
        Serial.println(lfr);
    }

    if (receivedDone){
        clearValuesToReceiveFrame();
        processFrame();
        receivedDone = false;
    }
}

Serial.println();
Serial.println("[While]n:");
Serial.println(n);
Serial.println("[While]LFR: ");
Serial.println(lfr);
n=0;
lfr=0;

}

in this block i learn to the programe that the posion 2 in my array is the lenght of the frame in API MODE:

        if ( n == 3 ){
        lfr = frameReceived[2] + 4;
    }

here i learn to the programe that the n number of bytes have to equal lfr (lengh of the data). if this is true my flags gonna work.

        if (n == lfr){
        receivedDone = true;
        Serial.println();
        Serial.print("[INFO] N: ");
        Serial.println(n);
        Serial.print("[INFO] LFR: ");
        Serial.println(lfr);
    }

    if (receivedDone){
        clearValuesToReceiveFrame();
        processFrame();
        receivedDone = false;
    }
}

the problem is that the program only rad 63 n number and my LFR is diferent so the flags never going true, n numbers ever is 63 from 78 real bytes :(
please help me.


texts: My project is based on controlling a moving fan using different hand gestures. I am using image processing toolbox from matlab to detect and identify various hand movements.I want to link my matlab codes to arduino for hardware implementation. How to link these two?


texts: Multidimensional array with date and numbers

texts:
I would like to create something similar to a multidimensional array.
I would like to get this effect.

setting = [
     0 => [// 0 is the day of the week, but it can be a number
         '1:25' => 25, // key is time. The value is a number (temperature)
         '7:12' => 22,
         '15: 30 '=> 21,
         '18: 00 '=> 23
         '22: 25 '=> 22
     ]
     1 => [
         '1:25' => 25,
         '7:00' => 21,
         '15: 00 '=> 22,
         '18: 00 '=> 25
         '22: 25 '=> 22
     ]
     2 => [
         '1:25' => 25,
         '7:00' => 21,
         '15: 32 '=> 21,
         '18: 40 '=> 25
         '22: 25 '=> 22
     ]
     .
     .
     .
     e.t.c
];

Then I would like to read these values. Days of the week and time are already downloading, but I do not know how to make such a board. I would like to download these values (temperature) to a variable.
Regards


texts:
I am trying to upload a sketch and getting below error:

error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed.

Connections:

TX - TX
CH_PD - 3.3 V
RX - RX
VCC - 3.3
GPIO GND
GND - GND

Before uploading the sketch I have reset the arduino and ESP and selected board as ESP8266 and baud rate as 115200 but still getting the same error.


texts: Send HTTP request from Arduino UNO+ESP8266

texts:
I am trying to send an HTTP request from from an Arduino UNO through an ESP-01 connected by Serial.
Communication with the ESP and connection to the AP work fine. But when i try to send an HTTP request to a server, it fails with a strange response from the ESP:

What are those strange characters coming from the ESP ?

(Note that other characters are mistaken as well, like the "http://xxx.col" instead of "http://xxx.com")
Here is the code I am using:

#include <SoftwareSerial.h>
#define RX 10
#define TX 11
String AP = "xxx";
String PASS = "xxx";
String HOST = "\"http://xxx.com\"";
String PORT = "80";
String tcp = "\"TCP\"";
String field = "field1";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
int valSensor = 1;
SoftwareSerial esp8266(RX,TX);

void setup() {
  Serial.begin(115200);
  esp8266.begin(115200);
  sendCommand("AT",5,"OK");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}
void loop() {
 sendCommand("AT+CIPMUX=1",5,"OK");
 //String connection = "AT+CIPSTART="+ tcp +"," + remoteip + "," + portnum + "\r\n");

 String getData = "GET battery/add.php?RAWVOLT=99&VOLT=99&RAWCURR=99 HTTP/1.0\r\n"; //this is mockup data for testing purpose
 getData += "Host: xxx.000webhostapp.com\r\n"; // add the required header
 getData += "\r\n";

 sendData("AT+CIPSTART="+ tcp +"," + HOST + "," + PORT + "\r\n",150000,true);
 sendData("AT+CIPSEND=0," +String(getData.length()+4),4000,true);

 //sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
 esp8266.println(getData);delay(1500);countTrueCommand++;
 sendCommand("AT+CIPCLOSE=0",5,"OK");
}

 void sendCommand(String command, int maxTime, char readReplay[]) {
   ***similar to sendData below***
 }

 String sendData(String command, const int timeout, boolean debug)
{
    String response = ""; // ESP8266 sendData String
    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {
        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }
    return response;
}


texts: Get board.vid and board.pid value in code

texts:
I'm working on a custom Arduino core based on the teensy code and want to be able to get the board USB VID/PID from boards.txt, as in .board.vid and .board.pid

From what I can tell, Arduino already does this for the Leonardo and similar since if I change the VID/PID in boards.txt then the sketch will run with those values.

But how do I actually get at them? Right now the code I have has hard coded values, but it would be great to make them dynamic.


texts:
In this project I will be using multiple ESP8266 WiFi modules (4) connected by software serial to an Arduino Leonardo Micro (1 UART). I plan to rotate between all 4 (starting with 2): Open port, write, read response, close port, move on....

This is a very barebones version of my code to address this one issue. Works flawlessly with a single (always open) connection, but it does not work when I close Ser1 (even if I don't start Ser2!!!)
Is the xxxx.end(); command broken or something?
Or am I doing something wrong? :/

Note: This code sends "AT" to the module, it responds with "OK"

When adding Ser2, LED flashes on Arduino periodically indicating it is writing to serial monitor, but nothing appears...

Code:

#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {

  pinMode(10, INPUT);
  pinMode(16, INPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, OUTPUT);
  Serial.begin(9600);
  //Set up Serial Monitor on host computer

}

void loop()
{

  delay(1000);

  Ser1.begin(9600); // open Ser1

  Ser1.write( 'A' );
  Ser1.write( 'T' );
  Ser1.write( '\r' );
  Ser1.write( '\n' );   // sends the line: "AT" with appropriate format

  Ser1.listen(); // make sure it's listening

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Ser1.end(); //close Ser1 port
  //This breaks the code for some reason....

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.begin(9600); // open Ser2

  Ser2.write( 'A' );
  Ser2.write( 'T' );
  Ser2.write( '\r' );
  Ser2.write( '\n' );

  Ser2.listen();

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }

  Ser2.end();

}


texts: device signature 0x000000 when burning bootloader

texts:
I receive this message: "device signature 0x000000" when a try to burn the bootloader on a atmega328p-au (SMD) inserted on PCB
i am using arduino uno as isp i already uploaded the ArduinoISP sketch and i check "Arduino as ISP" as programmer  with "arduino nano" as board
i do not know what is the problem i tried to check the ISP wiring with the arduino uno and everything is alright
what i noticed is that when i remove the GND wire attached to ISP the pin13 of the arduino lights up when i connect it it lights off i do not know what to do
here is the full schematic
Thank you for helping me


texts: Yet another display 16x2 not working with arduino

texts:
I found hundreds of questions about display not working with arduino.
However, no matter how trivial this looks like I am having the same problem I cannot understand by reading the other posts.

I have an Arduino micro connected to a display from the adafruit kit

RGB LCD SHIELD KIT W/ 16X2 CHARACTER DISPLAY

I haven't been able to understand whether positive or negative, but I think from the picture is RGB positive.

I have connected everything as shown in the diagram in this page:

LCD "Hello World!"

Obviously changing the pins as I have

RS at 8
E at 7
d4 = 12
d5 = 11
d6 = 10
d7 = 9;

The potentiometer changes the contrast, if I saturate it I can see the black boxes.

In the code put this as

const int rs = 8, en = 7, d4 = 12, d5 = 11, d6 = 10, d7 = 9;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

I checked with the multimeter whether the soldering is good and it carries the signal at the end of the wires.

and the rest as the example in the link,

This is my mess (please ignore the other arduino and the thermocople which is not connected, the other orange wire goes to GND of the Arduino).

Any ideas that might help?


texts: Accessing Values From Array Within a Library

texts:
There are many great examples of how to access information from an array on the net. I ran into a specific case that has me confused. I am using a library for attiny 85 TinyPpmReader.h. This is a simple library that will take PPM signals in from a RC receiver running in pulse position mode and allows you to attach to a pin to process input. Easy enough.

In the code below, I ran into some confusion when trying to access the data in the array. I am trying to filter out a single channel in the ppm stream and print the contents of only 1 channel (Original example prints 8 channels) and eventually map that value to a servo. (I pasted the serial monitor ouput at the end of the code)

I tried accessing the variable stored in the array like this:

void loop()
{
for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */

if(TinyPpmReader.detectedChannelNb == [5]) //Is this channel 6 in index 0-7?
{
Serial.println(TinyPpmReader.width_us[5); // if so, print only index 5 containing channel 6 values
}
delay(500);
}

Example unedited sketch from library

#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

#define PPM_INPUT_PIN  2

void setup()
{
  Serial.begin(38400)
  TinyPpmReader.attach(PPM_INPUT_PIN);
}

void loop()
{

  Serial.print(F("* Period="));Serial.print((int)TinyPpmReader.ppmPeriod_us());Serial.println(F(" us *"));
  Serial.print(F("ChNb="));Serial.println((int)TinyPpmReader.detectedChannelNb());
  for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */
  {
    Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us"));
  }
  delay(500);
}

The serial monitor prints this:

* Period=17928 us *
ChNb=8
Ch=1496 us
Ch=1744 us
Ch=896 us
Ch=1560 us
Ch=1640 us
Ch=1496 us
Ch=1536 us
Ch=1688 us

Any suggestions? It is probably something simple but I dont think I am googling the correct question to get the correct answer.

EDIT: That worked Mark!

New Code Mapping attempt (Compiles,does not work)

#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

//int potpin0 = 3;    <---------          // This worked
int val0;                     // integer to store value

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

void setup()
{
  setupServos();
}

void loop()
{
  val0 = analogRead(PPM_INPUT_PIN);  <---------          // reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
  val0= map(val0, 1000, 2000, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)
       // scale it to use it with the servo (value between 0 and 180)

moveServo(PANSERVO, val0);

  delay(5);                           // waits for the servo to get there
}


texts: Can anyone help me figure out why this buffer is overflowing? (Updated)

texts:
This should be fairly straightforward, but there must be something I'm not understanding about buffers.

I have serial data coming in to my Mega via Zigbee. I'm sending a string just like this: ~-0.6016800, where ~ is my unique starting delimiter and my end delimiter is a carriage return \n. I'm sure it's coming through the zigbee correctly, because I can see my string show up looking good in XCTU when I plug the zigbee into the PC. Here is my code:

const int numChars = 15;
char incoming[numChars];

static boolean Receiving = false;
static byte ndx = 0;
char startMarker = '~';
char endMarker = '\n';
byte K;
bool allreceived = false;

void Get() {
    memset(incoming, NULL, strlen(incoming));
    while (allreceived == false) {
        if (Serial.available() > 0) {
            K = Serial.read();
            if (Receiving == true) {
                if (K != endMarker) {
                    incoming[ndx] = K;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars-1;
                    }
                }
                else {
                    incoming[ndx] = '\0'; // terminate the string
                    Receiving = false;
                    ndx = 0;
                    allreceived = true;
                }
            }
            else if (K == startMarker) {
                Receiving = true;
                ndx = 0;
            }
        }
    }
}

So somehow my buffer is overflowing or something, no matter how big I make it. I see the array start off as I expect it for the first few characters, then it turns into unintelligible characters. I think part of the problem might be that the serial data is coming through at a different rate or something, because I can see my starting delimiter ~ on my LCD screen in the middle of my array. The way it's set up, I should never be able to see my start delimiter unless I miss my end delimiter without ending the array. (Note- I've tried different unique end delimiters too, but this seems to work just the same)

Any ideas on what might be causing this??

EDIT: NOW TRYING THIS CODE- I'm still having the buffer overflow, and I'd be really grateful if someone could take a look.

Sending code:

void PayloadSendit(void) {

Payload[0] = '~';  //1 char unique start

if (outFormat == 0) {
    Payload[1] = '0';
    Payload[2] = '$';  //spacer
    strcat(Payload, stringval); //5 char for hashmarks
}
else {
    Payload[1] = '1';
    strcat(Payload, stringvalin);  //6 char for inch
}
if (dotpos <= 99) {
    Payload[8] = '@';  //spacer
    char dotpos2[2];
    sprintf(dotpos2, "%i", dotpos);
    strcat(Payload, dotpos2);    //2 char
}
else {
    char dotpos3[3];
    sprintf(dotpos3, "%i", dotpos);
    strcat(Payload, dotpos3);   //3 char ///////////////////////////
}

Payload[11] = '0';  //1 char for "no errors" code
Payload[12] = '*';  //1 char end delimiter
Serial.println(Payload);
Serial.flush();
memset(Payload, '\0', 13);

}

Receiving code:

  void Get2() {
    memset(Payload, '\0', bufsize);
    while (allreceived == false) {
        int K = Serial.read();
        switch (K) {
        case -1: // Nothing to read
            break;

        case '~': // Starting a new string
            Receiving = true;
            break;

        default: // Any other characters.
            break;

        }
        if (Receiving) {
            for (int i = 0; i <= 10; i++) {
                Payload[i] = Serial.read();
            }
            if (Serial.read() == '*') {
                Receiving = false;
                allreceived = true;
            }
            else { memset(Payload, '\0', bufsize); }  //destroy array if end delimiter not where it should be
        }

    }
}


texts: Port Manipulation - fastest implementation

texts:
I'm working on an Arduino program but am getting bogged down on what is the 'correct' implementation. I understand that multiple versions may work, so for my needs the 'correct' version will be the fastest (i.e. executing in the fewest clock cycles)

I need to set three analog input pins on my Mega 2560 - let's call them PF2-0.

I could use pinMode() - but that performs some extra checks that I want to leave out.
I could use _BV() in the process, but that's another function call I wish to avoid.

So, using port manipulation, I can write:

DDRF = 0x07; //PF2, PF1, PF0 as input
PORTF = 0x07; // Disable pullups

This should configure my three pins as inputs - and reduce any extraneous function calls. This should even be faster than writing:

DDRF = (1 << PF2) | (1 << PF1) | (1 << PF0)

Is this the fastest implementation?

*To be honest, I'm not sure how to profile this to know for sure.


texts: W5100 Ethernet Shield to Custom Board Problem

texts:
I've been using an Arduino Ethernet shield and an Arduino Mega in my project, but now I'm trying to migrate all the components onto my own PCB. My board uses a W5100 same as the Arduino, but nothing shows up when I connect Ethernet to my computer. Even if there is no communication with the MCU the W5100 should show up as a network device and starting pinging.

I have spent A LOT of time troubleshooting this issue, and I would like to confirm one thing. Using the factory default register settings, I should be able to just connect the W5100 to my computer, and it will start pinging back and forth and be identified as a network device . . . assuming I have the circuit set up correctly just like the Ethernet shield. I used a combination of the recommendations from Wiznet and the Arduino Ethernet shield schematic to make mine.

Edit:
Here is my schematic for the Ethernet module. The question I'm really trying to get answered first is regarding the default state of the W5100. Do I need to set some registers or something to get the W5100 in the same state it is in on the Arduino shield?


texts: I am making heated socks with adjustments by Nano and want to extend batterty life?

texts:
I want to set a temperature and have Nano turn on for 2 minutes then off for 2 minutes and repeat using the same temperature originally set and have the ability to change temperature settings and do the same.
The following sketch works along with displaying battery voltage using MIT Inventor 2 app via Bluetooth HC-05 to my Android phone (without the on/off sequence I am looking to do).
I hope to keep my feet warm but also extend the battery life.  Can you tell me what methods I should research to figure out how to do this? I have looked at millis(), blink without delay, and my own limited programming skills without success.  Thanks.
#define right 5
#define left 6

int leftval = 0;
int val=0;
int vg=0;

void setup() {
  Serial.begin(9600);
  pinMode(left, OUTPUT);
  pinMode(right, OUTPUT);
  pinMode(A0, INPUT);
}

void loop() {
  int vg = analogRead(A0);
  Serial.println(vg / 82.049, 1);
  delay(200);
  if (Serial.available() >= 2) {
    unsigned int a = Serial.read();
    unsigned int b = Serial.read();
    unsigned int val = (b * 256) + a;

    if (val >= 0 && val <= 255) {
      analogWrite(right,val);
      delay(200);
    }

    if (val >= 1000 && val <= 1255) {
      leftval = val - 1000;
      analogWrite(left, leftval);
      delay(200);
    }
  }
}


texts: How would I give an Arduino-based product WiFi credentials?

texts:
Let's imagine I create this cool little Arduino-based (replace Arduino with any embedded system that's not a Raspberry Pi) object that does some interesting things but it needs an internet connection to retrieve some information. The object doesn't have an input interface for the user because it would be meaningless if not for the WiFi credentials insertion procedure. In my testing instance, I can just hardcode the credentials before flashing the firmware, but what if I wanted to make it a product and have every user set it up on his own network?

How was such a task handled in some commercial products with similar challenges? Or what would the best way of handling it be?


texts: Exiting from one loop and get ready for another

texts:
I am working on a keypad password lock system based on arduino UNO. I have used the password library from Arduino's website.

What I am trying to accomplish is to set two passwords, namely pass1 and pass 2.

The condition is that this circuit is attached to a gate, if user 1 lets say knows pass1, after entering the pass the gate will unlock for 10 seconds and the pass1 becomes invalid i.e. can not be used in future. However if user 2 comes and knows pass2, after entering the pass2, the gate will open for 10 seconds and then pass2 becomes invalid; so each password can be used only once. I am attaching the code I already have below.

The problem with this code is that when pass1 is executed, the system does not take pass2 until unless the system is reset.

Kindly tell me a solution to fix this.

#include <Password.h>
#include <LiquidCrystal.h>
#include <Password.h>
#include <Keypad.h>

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
Password password1 = Password("1234");
Password password2 = Password("4567");
int ledpin = A5;
int a = 0;
const byte ROWS = 4; // Four rows
const byte COLS = 4; // columns

char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
};

byte rowPins[ROWS] = {A0, A1, A2, A3};
byte colPins[COLS] = { 8,  9, 10, 11};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup() {
    lcd.begin(16, 2);
    keypad.addEventListener(keypadEvent); //add an event listener for this keypad
}

void loop() {
    keypad.getKey();
}

void keypadEvent(KeypadEvent eKey) {
    switch (keypad.getState()) {
        case PRESSED:
            lcd.println(eKey);
            switch (eKey) {
                case '*':
                    checkPassword();
                    break;
                case '#':
                    password1.reset();
                    password2.reset();
                    break;
                default:
                    password1.append(eKey);
                    password2.append(eKey);
            }
            return;
    }
}

void checkPassword() {
    if (password1.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code1 OK");
        delay(2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password1.append('1');
        lcd.clear();
        return;
    } else if (password2.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code2 OK");
        delay (2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password2.append('2');
        lcd.clear();
        return;
    } else {
        lcd.setCursor(0, 1);
        lcd.println("Wrong");
        delay(2000);
        lcd.clear();
        lcd.print("Wait for 5 Sec");
        delay(5000);
        lcd.clear();
        return;
    }
    return;
}

Regards
Fawad


texts: Arduino accepting only alternate characters

texts:
I am writing an Arduino code to receive SMS from a SIM800 module and then send the same message back to the sender. My code is as follows:

#include<SoftwareSerial.h>

SoftwareSerial mySerial(9, 10);//Connect to pin 9&10 on GSM module

const byte numChars = 128; //character size
char receivedChars[numChars]; // Store data read from SMS
boolean newData = false; //flag to check if new data has arrived

void setup() {
 Serial.begin(9600);
 mySerial.begin(9600);
 Serial.println("<Arduino is ready>");
 mySerial.println("AT");
 mySerial.println("AT+CMGF=1"); //text mode
 mySerial.println("AT+CNMI=1,2,0,0,0");
 mySerial.println("AT+CSQ"); //Check signal strength
   while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

void loop() {
  //code for checking sms
  scanSMS();
  //Print if a new data arrived
  showNewData();
  delay(25000);
}

void scanSMS() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '#'; //Start and end markers. Eg. SMS body will be sent as #status#
    char endMarker = '#';
    char rc;
    while (Serial.available())
    {
      mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
    }

    while (mySerial.available() > 0 && newData == false) {
      Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port

      rc = mySerial.read();

      if (recvInProgress == true) {
        if (rc != endMarker) {
          receivedChars[ndx] = rc;
          ndx++;
          if (ndx >= numChars) {
            ndx = numChars - 1;
          }
        }
        else {
          receivedChars[ndx] = '\0'; // terminate the string
          recvInProgress = false;
          ndx = 0;
          newData = true;
          }
        }
      else if (rc == startMarker) {
        recvInProgress = true;
      }
    }
}

/*PRINT IF THERE IS A NEW DATA*/
void showNewData() {
 if (newData == true) {
   SendMessage(receivedChars);
 newData = false;
 }
}

/*SEND BACK WHATEVER SMS IS RECEIVED*/
void SendMessage(String receivedChars)
{
  Serial.print("here");
  mySerial.println("AT+CMGS=\"+xxxxxxxxxx\"\r"); // Replace x with mobile number
  mySerial.println("Humidity Alert!");// The SMS text you want to send
  mySerial.print(receivedChars);
   mySerial.println((char)26);// ASCII code of CTRL+Z
}

The issue is that the module seems to receive only alternate characters instead of the whole message. For example, if I send the text #program#, the Arduino will only print porm or rga. Am I missing something here? Any help is highly appreciated.


texts: Add a watermark to text message in an Arduino

texts: I'm trying to add a watermark to the text in the Arduino and there are several levels of watermarks (fragile, semi-fragile, robust). What is the difference between these levels in terms of algorithms used?


texts: Splitting a string read from Serial into parts

texts:
Is there any method with which I can split a string given by Serial.read() into an array of 3 items: [command, address, message], to write it to EEPROM?

Thanks.


texts: How to return the value in Arduino function (that can be read by the connected device)?

texts:
Right now I have an RC car program for Arduino. The code is like this:

void loop() {
  distance = Dist.getDistanceCentimeter();
  if(distance<=5 & distance>1)
  if(Serial.available()) {
    lkf = Serial.read();
  switch(lkf) {
  case 'a':
     forward();
     servoX.write(90);
     lkf=0;
     break;
  }
}

I wrote a TCPclient that can order the RC car to move forward by connecting through TCP and sending the message "a" to the Arduino board.

The problem is how to return the distance to the cilent? Is it simply return distance; or something like system.println(distance);? Thanks for helping.


texts: DC motor does not work using PWN or Digital pins

texts:
I have connected pin 3 to a DC motor and using analogWrite and DigitalWrite to try making it start. However, nothing happens.
If I try to move the pin from pin 3 to 5V or 3.3V the motor starts.

Q: What could be the problem since it does not start using pin 3 (or others). I am using HIGH on digitalWrite and 255 on analogWrite.

I just bought a starter kit. It has FREENOVE written on it.
Here is a link to the tutorial and software.

Thanks for any help!


texts: Stepper motor based clock movement with DS3231

texts:
I am working on a clock movement that is powered using a stepper motor and the GSM2 driver board. The delay between steps needed to achieve 1 rpm on the second hand works out to 25 ms. In my current setup, I am sending pulses to the driver board using the delay() function. This works reasonably well, although it is not accurate enough for me. To remedy this problem, I ordered a DS3231 RTC module, thinking I could use that to replace delay()/millis(). However, I can't figure out how to achieve millisecond resolution using the RTC. It seems like it should be strait forward given the oscillator on board the RTC is 32kHz. I am new to arduino programming and am out of my comfort zone with this one.

Does anyone know of a way to achieve the 25 ms pulses we need while still retaining the accuracy of the RTC? Is it possible to use the RTC to correct the output produced by the built in delay()/millis() function? How would you then translate that output to pulses sent to the stepper motor driver board?

Internet research produces some mixed results on whether or not this is possible. I have yet to see an example of a clock with millisecond resolution. The theory behind it makes sense, but I don't know where to start.


texts: Interfacing Arduino nano ,adxl335 ,nrf24l01

texts: I'm trying to make a project with this conection diagram  but I don't think it's correct , and my adxl sensor died . Can you help me with a modified one ?


texts:
I'm trying to do a data logger. Writes into SD card has to stop when millis()=1000. Maybe I have a problem between millis() and my interrupt, because datalogger doesn't stop after millis()=1000. I'm working with Arduino Mega.

#include <SPI.h>
#include <SD.h>
volatile unsigned int cuenta = 0;
unsigned char contador = 0x00;
const int chipSelect = 53;
long currentMillis = 0;
long previousMillis = 0;
long interval = 1000;

void setup() {
  DDRA = B11111111;
  cli();//stop interrupts
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 10000khz increments
  OCR0A = 25;// = (16*10^6) / (1000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);
  sei();//allow interrupts
  //periodo de cada pulso 255ms del tren total de pulsos aproximadamnte 255ms
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  Serial.println("card initialized.");
}

ISR(TIMER0_COMPA_vect) {
  cuenta++;
  if (cuenta > 9) {
    PORTA = ++contador;
    cuenta = 0;
  } else {
    PORTA = 0X00;
  }
}

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis <= interval)
  {
    String dataString = "";
    for (int analogPin = 0; analogPin < 1; analogPin++) {
      int sensor = analogRead(analogPin);
      dataString = String(sensor);

      if (analogPin = 1) {
        dataString += ",";
      }
    }
    File dataFile = SD.open("datalog2.txt", FILE_WRITE);
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      Serial.println(dataString);
    }
    else {
      Serial.println("error opening datalog.txt");
    }
  }
}


texts: How to acheive fast and reliable communication between NodeMCUs?

texts:
I have two NodeMCU which have to send data to a server (also a NodeMCU). I want to acheive speed of atleast 10Hz because the sensor sends it at that rate. I have  tried websockets and couldn't get transfer rate of more than 1Hz and the data was being put in the buffer.

Any ideas how could I can acheive speed of 10Hz via WiFi?

Thanks for any help.


texts: Newbie question: Set servo at certain degrees when something happens

texts:
I am trying to set my servo at f.e. 90 degrees when the friendlyValue of the soil sensor is < 50%. The servo isn't moving at all, is it because the code is running too fast and the servo doesn't have time to reposition in between? I tried putting in delays but that didn't work, how do I fix this?
I am new to Arduino and would appreciate any help.

#include <Servo.h>
Servo myservo;

int dryValue = 1024; // max
int wetValue = 0; // min

int friendlyDryValue = 0; // %
int friendlyWetValue = 100;

int sensor = A0;
int sensorValue;

void setup() {

  Serial.begin(115200);

  pinMode(A0, INPUT);
  pinMode(D6, OUTPUT);
}

void loop() {

  int rawValue = analogRead(A0); // soil sensor

 Serial.print("Raw: ");
  Serial.print(rawValue);
  Serial.print (" | ");

   int friendlyValue = map(rawValue, dryValue, wetValue,     friendlyDryValue, friendlyWetValue);

  Serial.print("Friendly: ");
  Serial.print(friendlyValue);
  Serial.println("%");

if (friendlyValue <50)
{
  myservo.write(9);
  }
  else
  {
    myservo.write(90);
    }
  }


texts: How to send data to sim900 only once in loop()

texts:
I am trying to communicate with a client(PC) from my arduino (set up as a server with a sim900 module connected via UART). I have successfully got it to register its IP address with a dynamic DNS provider (no-ip.com) and set up a TCP server using the AT+CIPSERVER command for the sim900. All this is done in setup(). After that in loop() it waits for a client to connect. The moment a client connects the problem arises. The code is:-

void loop()
{
  while(Serial.available() <= 0);
  int x=0;
  char server_recv_string[30];
  while(Serial.available()>0)
  {
    server_recv_string[x] =  Serial.read();
    delay(10);
  }
  Serial.println(server_recv_string);
  sendATcommand2("AT+CIPSEND",">","ERROR",1000);
  sendATcommand2("I hear you\x1A","SEND OK","ERROR",5000);
  while(Serial.available()>0)  // I dropped this in to clear out the input buffer.
  {                            // Doesn't help
    Serial.read();
    delay(10);
  }
  Serial.flush();
}

The sendATcommand2 is a function as given below. I don't think that has any fault in it because it seems to work fine for all the other commands in setup. However this is the code:-

int8_t sendATcommand2(char* ATcommand, char* expected_answer1,
    char* expected_answer2, unsigned int timeout){

    uint8_t x=0,  answer=0;
    char response[100];
    unsigned long previous;

    memset(response, '\0', 100);    // Initialize the string

    delay(100);

    while( Serial.available() > 0) Serial.read();    // Clean the input buffer

    Serial.println(ATcommand);    // Send the AT command

    x = 0;
    previous = millis();

    // this loop waits for the answer
    do{
        // if there are data in the UART input buffer, reads it and checks for the answer
        if(Serial.available() != 0 && x < 100){
            response[x] = Serial.read();
            x++;
            // check if the desired answer 1  is in the response of the module
            if (strstr(response, expected_answer1) != NULL)
            {
                answer = 1;
            }
            // check if the desired answer 2 is in the response of the module
            else if (strstr(response, expected_answer2) != NULL)
            {
                answer = 2;
            }
        }
    }
    // Waits for the asnwer with time out
    while((answer == 0) && ((millis() - previous) < timeout));

    return answer;
}

The when I monitor it on the serial terminal I get infinite sends to my client. Its like this:

 AT+CIPSEND
 I hear you

 AT+CIPSEND
 I hear you

 AT+CIPSEND
 I hear you

 AT+CIPSEND
 I hear you

 // And on and on and on.

Any idea why this is happening? If you guys need any more information, please do tell me.

Thanks

Taz


texts: im using the l298n module, and 3x 18650 batterys (near 12v total), and supplying 12v to the 12v pin of the l298 module. Can i use the 5v pin of the module to power the 5v pin of arduino? Or i need a second power supply just for the arduino? Any tips?


texts: Ways of communication between two Arduinos?

texts:
I have two circuits one having a ultra sound sensor and one other having a relay module. So i'm trying to establish communication between the two to send and recieve data. I just want to know which way is the best so that one arduino will send data only when the other is powered and able to recieve data. So that there is no problem when one circuit is powered on and the other is not and the data is not sent until the connection between the two is established .This is because the circuits are powered by different power sources and the current is not predictable and i dont want any miscommunication happening between them.
any way is okay like rf or wifi or some other methods? Using other devices is also an option like ESP32 which has builtin wifi and bluetooth, But wired is not possible because the distance is too big like about 15-17 meters and using the same power source is not viable for the same reason. Tell me also if the distance im worried about is not a problem?


texts: Forcing bootloader startup through program

texts:
I am trying to find out if it is possible to trigger programmatically the double-tap on reset button function, implemented in modified version of Atmel's SAM-BA bootloader. The board of interest is Arduino Zero.
In case this is not possible using the stock board setup, if this can be achieved by hardware or bootloader modifications.


texts: Play sound with speaker inside interrupt while a timer runs

texts:
I'm attempting to start a timer lasting a specific interval when the ultrasonic distance sensor measures a distance lower than 25 cm. Once that occurs, I want the speaker to make sound if the distance goes above 25 cm whilst the timer is running. I am attempting to use an interrupt to do this, but I'm having trouble.

This is what I have so far:

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), sensor, CHANGE);
}

int makeSound() { // This function creates the sounds
  ...
}

int echo() { // This function gets the distance the sensor is measuring
  ...
}

void loop() {
  distanceCm = echo();
  if (distanceCm < 25) {
    Timer();
  }
}

int Timer() {
  half_hour_millis = millis();

  while (millis() < half_hour_millis + interval) {
    // Here goes the code that I haven't written and was hoping you could help me with
  }
}

// My interrupt function
void sensor() {
}


texts: PLX DAQ is logging data on the debugger but not diasplaying it on excel sheet

texts:
My code is this:

I tried to send arduino serial monitor data to plx daq but the sensor data is not displaying on excel.

#include "Wire.h" // This library allows you to communicate with I2C devices.
const int MPU_ADDR = 0x68; // I2C address of the MPU-6050. If AD0 pin is set to HIGH, the I2C address will be 0x69.
int16_t accelerometer_x, accelerometer_y, accelerometer_z, accelerometer_amp; // variables for accelerometer raw data

int16_t gyro_x, gyro_y, gyro_z; // variables for gyro raw data
int16_t temperature; // variables for temperature data

char tmp_str[7]; // temporary variable used in convert function
char* convert_int16_to_str(int16_t i) { // converts int16 to string. Moreover, resulting strings will have the same length in the debug monitor.
  sprintf(tmp_str, "%6d", i);
  return tmp_str;
}
void setup() {

  Serial.begin(115200);
  Wire.begin();
  Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
  Wire.write(0x6B); // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);

  //open serial connection
   // Serial.begin(115200);

    Serial.println("CLEARDATA");
    Serial.println("LABEL,Date,Time,");

}
void loop() {

  Wire.beginTransmission(MPU_ADDR);
  Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) [MPU-6000 and MPU-6050 Register Map and Descriptions Revision 4.2, p.40]
  Wire.endTransmission(false); // the parameter indicates that the Arduino will send a restart. As a result, the connection is kept active.
  Wire.requestFrom(MPU_ADDR, 7*2, true); // request a total of 7*2=14 registers

  // "Wire.read()<<8 | Wire.read();" means two registers are read and stored in the same variable
  accelerometer_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L)
  accelerometer_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x3D (ACCEL_YOUT_H) and 0x3E (ACCEL_YOUT_L)
  accelerometer_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x3F (ACCEL_ZOUT_H) and 0x40 (ACCEL_ZOUT_L)
  temperature = Wire.read()<<8 | Wire.read(); // reading registers: 0x41 (TEMP_OUT_H) and 0x42 (TEMP_OUT_L)
  gyro_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x43 (GYRO_XOUT_H) and 0x44 (GYRO_XOUT_L)
  gyro_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x45 (GYRO_YOUT_H) and 0x46 (GYRO_YOUT_L)
  gyro_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x47 (GYRO_ZOUT_H) and 0x48 (GYRO_ZOUT_L)

  //accelerometer_amp=   pow(pow(accelerometer_x,2)+ pow(accelerometer_y,2)+ pow(accelerometer_z,2),0.5);
//  print out data
 Serial.print("aX = "); Serial.print(convert_int16_to_str(accelerometer_x));
Serial.print(" | aY = "); Serial.print(convert_int16_to_str(accelerometer_y));
Serial.print(" | aZ = "); Serial.print(convert_int16_to_str(accelerometer_z));

//Serial.print(" | acc_amp = ");
//Serial.print(convert_int16_to_str(accelerometer_amp));

Serial.print(analogRead(int16_t));
  Serial.print(",");
  Serial.print(analogRead(int16_t));
  Serial.print(",");
  Serial.println(analogRead(int16_t));
  delay(1000);

  Serial.println();

  // delay
  delay(300);
}


texts: help please ion combination of two scetch

texts:
i have a two scetch working  the first one is set time with rtc matrix keypad to controll servo motor and the second one is HC-05 bluetooth module to controll servo using android app i want to combine those scetch can somebody help me i post my codes below

my first code was for setting time (components : lcd display , matrixkeypad 4*4, RTC realtime module, servo motor)

#include <DS3231.h>
#include <Servo.h>
#include <LiquidCrystal.h>
#include <Keypad.h>
#include <SoftwareSerial.h>
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Three

// Define the Keymap

char keys[ROWS][COLS] = {

  {'1','2','3'},

  {'4','5','6'},

  {'7','8','9'},

  {'*','0','#'}

};

// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.

byte rowPins[ROWS] = { 0, 2, 3, 4 };

// Connect keypad COL0, COL1 and COL2 to these Arduino pins.

byte colPins[COLS] = { 5, 6, 7 };

//  Create the Keypad
  Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

DS3231  rtc(A4, A5);
Servo servo_test;      //initialize a servo object for the connected servo
LiquidCrystal lcd(A0, A1, A2, 8, 12, 13); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)

 //int angle = 0;

// int potentio = A0;      // initialize the A0analog pin for potentiometer
 int t1, t2, t3, t4, t5, t6;

boolean feed = true; // condition for alarm

 char key;
 int r[6];

 void setup()
 {
  servo_test.attach(9);   // attach the signal pin of servo to pin9 of arduino
  rtc.begin();
  lcd.begin(16,2);
  servo_test.write(55);
  Serial.begin(9600);
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);

 }

 void loop()
 {

lcd.setCursor(0,0);
int buttonPress;
buttonPress = digitalRead(A3);

if (buttonPress==1)
 setFeedingTime();

//Serial.println(buttonPress);

 lcd.print("Time:  ");
 String t = "";
 t = rtc.getTimeStr();
 t1 = t.charAt(0)-48;
 t2 = t.charAt(1)-48;
 t3 = t.charAt(3)-48;
 t4 = t.charAt(4)-48;
 t5 = t.charAt(6)-48;
 t6 = t.charAt(7)-48;

 lcd.print(rtc.getTimeStr());
 lcd.setCursor(0,1);
 lcd.print("Date: ");
 lcd.print(rtc.getDateStr());

 if (t1==r[0] && t2==r[1] && t3==r[2] && t4==r[3]&& t5<1 && t6<3 && feed==true)
 {

  servo_test.write(220);                   //command to rotate the servo to the specified angle
   delay(8000);
  servo_test.write(75);
  feed=false;

 }
 }

void setFeedingTime()
{
  feed = true;
   int i=0;

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Set feeding Time");
  lcd.clear();
  lcd.print("HH:MM");
  lcd.setCursor(0,1);

  while(1){
    key = kpd.getKey();

    char j;

  if(key!=NO_KEY){

    lcd.setCursor(j,1);

    lcd.print(key);

    r[i] = key-48;
    i++;
    j++;

    if (j==2)
    {
      lcd.print(":"); j++;
    }
    delay(500);
  }

  if (key == '#')
  {key=0; break; }
  }
}

and my second code for bluetooth module (HC-05 and android app)

 #include <SoftwareSerial.h> // TX RX software library for bluetooth
 #include <Servo.h> // servo library
Servo myservo; // servo name
int bluetoothTx = 10; // bluetooth tx to 10 pin
int bluetoothRx = 11; // bluetooth rx to 11 pin
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup()
{
  myservo.attach(9); // attach servo signal wire to pin 9
  //Setup usb serial connection to computer
  Serial.begin(9600);
//Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}
void loop()
{
  //Read from bluetooth and write to usb serial
  if(bluetooth.available()> 0 ) // receive number from bluetooth
  {
    int servopos = bluetooth.read(); // save the received number to servopos
    Serial.println(servopos); // serial print servopos current number received from bluetooth
    myservo.write(servopos); // roate the servo the angle received from the android app
  }
}

i want to combine them can somebody help me to combine them ? please i beg you


texts: Why is there a plastic sleeve on my HC-05 bluetooth module

texts:
I would like want to know why the bluetooth module has a plastic sleeve covering it?

Is it possible to remove it?


texts: Why can't I see the serial plot with the following code for arduino?

texts:
const int GSR=A0;
int threshold=0;
int sensorValue;

void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){
  int temp;
  sensorValue=analogRead(GSR);
  Serial.print("sensorValue=");
  Serial.println(sensorValue);
  temp = threshold - sensorValue;
  }


texts: Does ADC conversion to a voltage rely on the actual value of the +5 V pin?

texts:
Questions:

Does the conversion of the ADC count to voltage depend on the actual voltage of the +5 V pin?
If yes, what is the accepted method of getting that voltage from the board?

Background/Detail:

I have a circuit in which I have an Arduino Nano (clone) running from a USB connector (from a hub). The job of the Arduino is to measure the voltage on a battery which will drive a second circuit switched on/off by the Nano. For reference it is a battery tester.

There is a Nokia 5110 screen which displays the voltage from the very simple sketch below.

void setup() {
  Serial.begin(9600);
  display.begin();
  // Init done

  // You can change the contrast around to adapt the display
  // for the best viewing!
  display.setContrast(50);

  // Text display tests
  display.setTextSize(1);
  display.setTextColor(BLACK);
}

void loop() {
  display.clearDisplay();   // Clears the screen and buffer
  display.setCursor(0,0);
  display.print("Vin=");
  int rawVIN = analogRead(VIN);
  float floatVin = (rawVIN*4.75)/1023.0;
  display.println(floatVin);
  Serial.println(rawVIN);
  display.display();
  delay(1000);
}

I measured the voltage of the battery using a DVM and it is 4.13 V, yet
the Nano reports 4.35 V.
I have a common ground between the battery and Arduino.
Because the connection to test the voltage can float, I have a pulldown resistor to stop wild fluctuations (>10 kΩ)

After some investigation I found that the +5 V was actually outputting 4.75 V and changed my sketch from

float v = (rawVIN*5.0)/1024.0;

to

float v = (rawVIN*4.75)/1024.0;

and the voltage reading on the Arduino was now correct. I did this not because I understand what I did, I did it because I had a hunch it might change the value to the correct one.


texts:
I have a Chinese Arduino nano clone, but I don't know if it's possible to connect the Arduino to external (5v) power and have a USB serial connection ongoing. I'm trying to make a PC controlled LED Strip that can also work on its own.

For example: the PC controls the Arduino sets it to a specific mode and I turn off the PC, but the Arduino should still be running even when the PC is turned off.

I'm new to the world of arduinos.

I'm planning to use this to control addressable LED RGB Strips and am planning to use a 4000mA max power supply.


texts: Arduino Uno with data logging shield has a problem switching power sources

texts: I have the basic Adafruit "Light & Temperature data logger Tutorial kit" made, and it works well when connected to a PC, but when I unplug the PC USB connection and hook it up to another power source, it will not launch and run by itself. I have reset both the logger and Arduino board reset buttons, but it does not seem to start recording data to a new file. One of my power sources was a Solar panel / Solar Lithium Battery charger  (with the "Power Boost 500 basic 5V boost board, and an another alternate power source was a 6 x AA battery holder with a barrel jack connector. What am I missing here? I'm a newbie! Thanks.


texts: I'm working on a Virtual Reality game. I want to detect the position or movement of most of the bones in the human body(e.g. Knees, elbows, shoulders, hands and legs). This person may wear special equipment. How should I detect this?? I also want to get the distances between a certain position(e.g. The Arduino board) and each bone. Any ideas?


texts: Arduino_Debug doesn't successfully upload sketch to Arduino if JAVA is not installed

texts:
I use arduino_debug to upload my sketch to an Arduino Mega 2560 and to an Arduino Due from my application (Windows).

I saw the following issue:

When JAVA is not installed or it was installed only after the Arduino SW installation, the command:

arduino_debug --port COM6 --upload mysketch.ino

doesn't successfully to upload the sketch. My Arduino is connected to COM6 (I verified it) and the sketch's path is correct.

I got the following output:

Initializing packages...

Preparing boards...

Verifying...

Sketch uses 6222 bytes (19%) of program storage space. Maximum is 32256 bytes.
Global variables use 318 bytes (15%) of dynamic memory, leaving 1730 bytes for local variables. Maximum is 2048 bytes.

Uploading...

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x87

An error occurred while uploading the sketch

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x87

Has anyone seen this issue? Does anyone know why JAVA must be installed?


texts: My bot arm building is complete, I'm using it with Arduino and 2 joysticks with 4 servos ( mg90s), running with the 9v battery, but still, the servos could not lift the bot arm once it is going down and the servo keeps fluctuating. It is a 3d printed bot so it is not so heavy. please help?


texts:
I am simply using the following code

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  // set the data rate for the HardwareSerial port
  Serial2.begin(115200);
}

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

the Connection is as follows
pin 16(D27) of esp32 - > Tx of Neo6M
pin 17(D14) of esp32 - > Rx of Neo6M

Now I am not getting any data in the serial monitor. The same module works with arduino with software serial.
I am completely new in this thing and office is keep asking about the progess.


texts: Nano resets or freezes on calling a function

texts:
I'm controlling a light bulb with my Arduino Nano from serial or RF (via nRF24L01+) and I'm passing the commands as a string. After I get all the variables (3 ints) I try calling the function execOrder but no matter what I put in there, the Arduino just hangs or resets. Code is as follows:

#define SSR 3
#define SW 4
#define nanoID 1
bool isPWM = false;
int value;

// Módulo RF
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
RF24 radio(9,10);
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
#define PayLoad 20

#include <MemoryFree.h>

void setup() {
  pinMode(SSR, OUTPUT);
  pinMode(SW, INPUT_PULLUP);
  digitalWrite(SSR, LOW);
  value = 0;
  Serial.begin(9600);
  Serial.println("------ CEACI SAS -- Controller Module ------");
  Serial.println("Module No: " + String(nanoID));
  // Inicializar RF
  Serial.println("Inicializando RF");
  radio.begin();
  radio.setRetries(15,15);
  radio.setPayloadSize(PayLoad);
  radio.setPALevel(RF24_PA_MIN);
  radio.setDataRate(RF24_250KBPS);
  radio.setCRCLength(RF24_CRC_16);
  delay(100);
  radio.openWritingPipe(pipes[1]);
  radio.openReadingPipe(1,pipes[0]);
  radio.startListening();
  //radio.printDetails(); //RF Debug
  Serial.println("RF listo!");
  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

void loop() {
  if (Serial.available()) {
    Serial.println("Rcvd Serial!");
    String msgRcvd = Serial.readString();
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else if (radio.available()){
    int RFlen=0;
    char msgBuff[]="";
    RFlen = radio.getDynamicPayloadSize();
    delay(10);
    radio.read(&msgBuff, RFlen);
    String msgRcvd(msgBuff);
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else {
    chkSwitch();
  }
}

void execOrder(int ID, int CMD, int VAL){
  if (ID == nanoID || ID == 0){
    switch(CMD){
      case 0:
        State();
        break;
      case 1:
        value = VAL;
        OnOff();
        break;
      case 2:
        value = VAL;
        PWM();
        break;
    }
  }
}

I wanted to process the incoming string in a function, but it resets as well.

By the way, I'm using MemoryFree library to check if I'm out of memory, and there's plenty of it, so I don't really know where's the problem. Any help would be greatly appreciated!

EDIT:

For the serial part I can do the following (my original code):

if (Serial.find("MOD=")) {
  int ID = Serial.parseInt();
  if (ID == nanoID || ID == 0) {
    Serial.find("CMD=");
    int command = Serial.parseInt();
    int cmdVal = 0;
    if (command != 0){
      Serial.find("VAL=");
      cmdVal = Serial.parseInt();
    }
    Serial.println("MOD: "+String(ID)+", CMD: "+String(command) + ", VAL: " + String(value));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    execOrder(ID,command,cmdVal);
  }
}

And it works flawlessly. But I don't know how to achieve the same results with the RF input. The problem seems to be with using so many strings.


texts: I am very confused with the pins on the arduino micro. What are the 3v3, 5v, and Vin pins used for? Are they for power input, or power output, or both?