texts: Stepper motor moves initially but after idle time, clicks and doesn't move for a while

texts:
I am using the Accelstepper library to control a stepper motor, according to commands input via Serial.
It works as expected for the first time when I start Serial Monitor and send command.

When left idle for some seconds (> 10 seconds), the motor makes clicking sounds for the first few commands(without moving) and then it starts working again as expected. The longer I leave it, the more commands it misses.

It gets resolved if I restart Serial Monitor on UNO.

#include <Arduino.h>
#include "AccelStepper.h"

#define STEPPER_X_STEP_PIN 2
#define STEPPER_X_DIR_PIN 3

enum Direction { FORWARD, BACKWORD } direction;

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

void blockingRunSpeedToPosition();

AccelStepper stepper(AccelStepper::DRIVER, STEPPER_X_STEP_PIN, STEPPER_X_DIR_PIN);

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(200.0);
  stepper.setAcceleration(50);
}

void loop()
{
  // print the string when a newline arrives:
  if (stringComplete) {
      // clear the string:
      inputString.trim();
      if(inputString == "x") {
          direction = FORWARD;
          blockingRunSpeedToPosition();
      }
      inputString = "";
      stringComplete = false;
    }
}

void serialEvent() {
    while (Serial.available()) {
        char inChar = (char)Serial.read();
        inputString += inChar;
        if (inChar == '\n') {
          stringComplete = true;
        }
    }
}

void blockingRunSpeedToPosition()
{
    int steps = 400;
    stepper.setCurrentPosition(0);
    stepper.move(steps);
    while (stepper.distanceToGo() != 0) {
           stepper.run();
    }
}

I think there is no issue with the code or my Arduino connection since the motor runs fine in the beginning.

I tried the above code on Arduino MEGA, UNO, different motors with different drivers. The problem persists.

I think it is something to do with motor excitation (energized coils).
Please give me some hints and pointer to debug the issue, since I don't know where to look. I am an intermediate programmer and robotics hobbyist.

Here is the video demo of the issue.

I am using:

Arduino MEGA - ATmega2560
NEMA 23.
Rino stepper motor.
Arduino Pin 2 is Step and 3 is Direction.
Driver Vcc is connected to 5V pin.
48 volt, 5 Amps SMPS.
Ubuntu 16.
Accelstepper library


texts:
I have a class named timeOut dealing with timeout tasks.

I'm to write a sketch, common for Sonoff basic and Sonoff Dual, meaning that I may have 1 task for Basic and 2 tasks for Dual.

Declaring instances looks like:

timeOUT timeOut_SW0("SW0",TIMEOUT_SW0);
timeOUT timeOut_SW0("SW1",TIMEOUT_SW1);

for code simplicity I'd rather create an array of references and call it using a for loop:

timeOUT TO[]={timeOut_SW0,timeOut_SW1};

is it the right way to call it as a reference ?


texts: Can anyone help me spot where my buffer overflow might be occuring?

texts:
I'm using dtostrf() to transcribe a float into a string for my touchscreen. I'd leave it as a float, but my screen orientation library function only works with a string.

So I have a char array, then a float value. then dtostrf().

char buffer[6]
float X; //changes each loop with incoming sensor data from pixy camera
float thingposition = X * .0064  //float calculations are performed.

void loop(){
Camera.Get_X();   //retrieves X from the camera. waits until X has been recieved via UART serial
dtostrf(buffer, 5, 2, thingposition) // writes float to string with a controled decimal place and all that - dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf);
Tft.drawString(buffer, 70, 215, 5, WHITE);   //print output to screen
}

Note that this is a simplified version. In my code I also have methods for overwriting my last string value on the LCD when the new one has changed.
I also have several "if" conditionals that control whether I write the buffer value to the screen or instead send an error message. Those things do not seem to be causing me problems though, except to say that my buffer overflows only occur when I cause the sensors to flip the conditionals at just the right interval.

For example, when I place my hand in front of the camera, that triggers the error message. Take my hand away, and then the number "thingposition" is printed to the screen. But if I time my hand just right, the buffer overflows and numbers loop across the screen. Usually this freezes the whole sketch. The best I can figure is that since dtostrf() does not check bounds, and since the calculated float values can be longer than the buffer has room for, that sometimes dtostrf() tries to write too many digits to the buffer. Something timing-related seems to trigger the problem, but what I need is some way to prevent the overflow in the first place.

I've tried rounding "thingposition" to a certain number of sigfigs, but I can't seem to truncate it at the desired decimal point. That shouldn't matter though, since dtostrf has controls for the minimum total length including the decimal point, as well the number of digits after the decimal. I also tried making sure that the last byte in my char array is null by adding this right after dtostrf():

stringval[5] = NULL;   //make sure buffer is null-terminated to prevent buffer overflow

I've tried doubles, different ways of rounding, and anything I could find, but the problem has persisted for several weeks and a few steady days worth of searching for a solution. I'll be glad to provide further information if anyone has any ideas on what to try. Thanks everyone.


texts:
I have searched about class and int but I still don't understand.

I have seen this code online I want to understand it

class Motor {

  int enablePin;
  int directionPin1;
  int directionPin2;
  public:

  //Method to define the motor pins
  Motor(int ENPin,int dPin1,int dPin2){
    enablePin = ENPin;
    directionPin1 = dPin1;
    directionPin2 = dPin2;
};


texts: MicroSD interfering with ISP programming

texts:
I have a microSD connected to an Arduino and I can't program it over ISP without removing the SD card. Does anybody know how to prevent the SD card from interfering with the ISP programming?

Details:

This is the microSD breakout: https://www.adafruit.com/products/254

I'm using an ATMEGA328P at 3.3V 8MHz.

I'm not using a bootloader and, for several reasons, I can't use the serial port for programming.

Thanks!


texts: Unable to get output on Arduino serial communication with ESP8266 and M6E RFID reader

texts:
I am unable to get the output on NODEMCU serial. NODEMCU is connected with Arduino Uno, and Uno is connected with M6E Nano RFID reader. Currently I am unable to understand that am i doing any mistake. Please let me know if any other thing you require.

NodeMCU and M6E Nano RFID reader pin configuration with Arduino Uno

NodeMCU         UNO
Vin             Vin
GND             GND
D2              2
D3              3

Code for Arduino Uno+M6E Nano RFID Reader

#include <SoftwareSerial.h>
SoftwareSerial softSerial(2, 3);

#include "SparkFun_UHF_RFID_Reader.h"
RFID nano;

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

  while (!Serial);
  Serial.println();
  Serial.println("Initializing...");
}

void loop()
{
  byte response;
  byte myTID[20]; //TIDs are 20 bytes
  char str[sizeof(myTID) * 2 + 1];
  const char* hex = "0123456789ABCDEF";

  //Read unique ID of tag
  response = nano.readTID(myTID, sizeof(myTID));
  if (response == RESPONSE_SUCCESS)
  {
    for (int i = 0; i < sizeof(myTID); i++)
    {
      str[i * 2] = hex[(myTID[i] >> 4)];
      str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
      }
    str[sizeof(str)] = 0;
    Serial.println(str);
   }
  else
    Serial.println("Failed read");
}

Code for NODEMCU

#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
SoftwareSerial NodeMCU(D3,D2);

void setup()
{
  Serial.begin(9600);
  NodeMCU.begin(4800);
  pinMode(D2,OUTPUT);
  pinMode(D3,INPUT);
}

void loop(){
  String str = 0;        // stores received byte

  if(NodeMCU.available())
  {
    // get byte from USB serial port
    str = Serial.read();
    NodeMCU.write(str);
  }
delay(30);
}

Unable to find where i am doing the mistake! Thanks in advance


texts: Does Proteus simulate external interrupts properly using Arduino? I can't get them to work

texts:
I am trying to simulate an interrupt with an Arduino Uno in Proteus. This is the simple test code that I'm using:

void introutine()
{
  digitalWrite(13,HIGH);
}

void setup()
{
  pinMode(13,OUTPUT);
  attachInterrupt(2,introutine,LOW);
}

void loop()
{
}

Here's the circuit in Proteus:

When I hit the button, the LED is supposed to turn on. Well, nothing happens. I have read something about Proteus being bad at simulating interrupts, but I'm not sure about it because Timer1 interrupts did work well. Basically, the problem lies within EXTERNAL interrupts only. I hope you people can help me.

Thank you.


texts:
I read and heard that the floating point math is much slower than int math.

And I saw a converting process in here floath math to integer math

So I want to to convert my floating math calculations to integer math.

Here is the code that include floating math:

float sensval, lpf, lps;
float sensinitial; // used to store the initial sensor data
float x, y, z;
int heigh;
int dA;

void setup() {

  runSensor();
  sensval = readSensorData();
  sensinitial = sensval; // Setting the initial data
  lpf = lps = sensval;
}

void loop() {
  sensval =  readSensorData();
  heigh = (float)44330 * (1 - pow(((float) sensval/sensinitial), 0.190295));
  lpf = lpf + (sensval - lpf) * 0.1;
  lps = lps+ (sensval - lps) * 0.05;
  x = (lps - lpf) * 50;
  y = x+ (z - y) * 0.1;
  z = constrain(y, -500, 500);
  dA += z * 100 + 2000;
}

readSensorData(); returns 7 decimals maximum(752.4543 for example)

There is pow calculation too.

So how can I convert floath math to int math?

Any optimization code are welcome.


texts:
I got an SD card breakout from an online shop, its the iteed kind without the level shifter, it has the 3.3 / 5 V switch. I cannot find any libraries or write example for it.

Has anyone dealt with it before with Arduino? I have tried finding info but I only get the level shifter kind that has the MOSI pins!

enter image description here


texts: How to avoid pulling the RX0 pin to reset sketch

texts:
My project requires reading 5 serial devices (RFID readers) at the same time. I chose an Arduino Mega 2560 as it comes with 4 serial RX ports. For the fifth port I am using the SoftwareSerial library.

My loop() checks each Serial port to detect if an RFID tag is being read. This works perfectly.

However, I am powering the board from an wall wart. When the power is disconnected the sketch no longer runs. I must unplug RX0, plug in the power supply, and reattach RX0.

If the board ever loses power it will have to be reset manually which is not ideal.

Please help me understand Why is this happening? and how can I fix it?


texts: Subtraction with doubles returning zero erroneously

texts:
I have a function that takes as parameter some doubles and does a subtraction operation on it. However I'm getting a result of 0 when one of the parameter is 0 for some reason.

int calcPID(double current, double desired, double k){
  double diff;
  diff = desired - current;
  Serial.print("desired = ");
  Serial.print(desired);
  Serial.print(", current = ");
  Serial.print(current);
  Serial.print(", diff = ");
  Serial.println(diff);
  int r = (int)diff;
  return r;
}

Output

desired = 250.00, current = 1.69, diff = 248.31
desired = 250.00, current = 0.00, diff = 0.00

When the current is 0.00 the result (diff) is also 0.00, when it should be 250. Can someone tell me what's going on?


texts: How do I save IR codes from my LG Air Conditioner remote and replay them?

texts:
I am currently using the following code

#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
 Serial.begin(9600);
 irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
 if (irrecv.decode(&results))
  {
   Serial.println(results.value, HEX);
   irrecv.resume(); // Receive the next value
  }
 }

The Serial Monitor is always returning "FFFFFFFF" no matter which button I press.
So I am unable to replicate the signal.

Seems that the IR library doesn't support my LG remote.

How do I save and replicate the signal in this case?


texts: Whats the function of the resistor between MCU and its Resonator in Arduino Mega?

texts:
I was looking Arduino Mega's schematic and I noticed a resistor between the MCU and its resonator. R3 in this image:

Why is it there and what is its function?


texts: Is there any library for use Arduino Uno with esp8266-01 module?

texts:
I have a Arduino Uno and the esp8266 module,(NOT THE SHIELD).

I was looking for some library that I could use to connect to Wifi and set a webserver, but I can't find anything. I just found for Arduino Wifi Shield which uses SPI.

It is possible to use arduino lets say to read a LM35 and then send that data to the ESP8266 module and serve it in a page as webserver?

I know that I can use AT commands with ESP8266 to connect to wifi and to create a server, but I cannot find any function to set the data to be served.

https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf


texts:
I am doing a project in which I need to have a stereo audio output in Arduino MKR Zero. The quality of the audio is not important: 8 bit, 44 kHz would be enough. Is it possible to use two combined PWM outputs to do that, maybe with the library TMRpcm (is it supported by MKR?)? Or is it a better solution to interface it with a I2S stereo DAC?

Thank you
Alessandro


texts:
I am working on development of alarm clock using Arduino.

No doubt RTC will be the best but it increases the Price of the project. Also I opened a digital clock (which I purchased online) and I see that there is only one IC (obviously it is covered with something black wax). But there was that one patch only.
So it seems it used only a controller or RTC. But with only RTC its not possible to control LCD. So it must be only a microcontroller

Now I have three options for maintaining time

I use RTC like DS3231
I use millis() function
I use timer and timer interrupts of micro controller for free running timer.

Can I get accurate time using micro controller.


texts:
The following code works on a range of Arduino's but not on ESP. It returns random data for ID and Pin. The other two fields are always empty.

I use the Arduino IDE for both the ESP and the Arduino's. It looks like the ESP has it's own idea when it comes to struct.

#include <RH_ASK.h>
#include <SPI.h>

#define BAUD 2000
#define RX 2
#define TX 5

RH_ASK driver(BAUD, RX, TX);

struct data {
  int id;
  int pin;
  int value1;
  int value2;
} myData;

void setup()
{
    Serial.begin(9600);
    Serial.println("Starting..");
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    if (driver.recv(buf, &buflen)) {

      memcpy(&myData, buf, buflen);

      Serial.print("ID: ");
      Serial.println(myData.id);

      Serial.print("Pin: ");
      Serial.println(myData.pin);

      Serial.print("Value1: ");
      Serial.println(myData.value1);

      Serial.print("Value2: ");
      Serial.println(myData.value2);

      Serial.println("");
    }
    yield;
}

Bad Data

ID: 263145
Pin: 18350364
Value1: 0
Value2: 0

Should be

ID: 1001
Pin: 4
Value1: 267
Value2: 843


texts: Arduino-Pyserial communication on Python 3, Windows machine: Pyserial.write() doesn't seem to do anything

texts:
I've recently gotten my hands on an Arduino (or rather a Genuino, but the overall architecture should be the same) UNO. I'm now using that Arduino to test how data is transmitted from a USB to Serial Connector to the Arduino.

I've already verified that data transmission from Arduino to the PC is possible, by using hTerm and PySerial. However, whenever I send data from Pyserial or hTerm, it doesn't show up in the Arduino serial terminal. Also, I'm using SoftwareSerial to set up a secondary serial terminal to see what the Arduino receives. (I'm using the standard serial port to send data to the terminal, and the SoftwareSerial Port to connect to the USB to Serial Connector.)

Here's my code so far:

Python side:

import serial
import time
import sys
import struct
ser = serial.Serial('COM3', 9600, timeout=0)
time.sleep(10)
while 1:
    print(ser.write(struct.pack('>B', 0)))
    time.sleep(2)
    print(1)
    sys.stdout.flush()

The Arduino side looks like this, and is essentially the default example:
https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
  // put your setup code here, to run once:
  if (Serial) {
    Serial.end();
  }
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Serial.println("Godnight moon!");

  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() {
  // put your main code here, to run repeatedly:
  mySerial.listen();
  if (mySerial.available() > 0) {
    Serial.println("Hello User");
    Serial.println(mySerial.read());
  }
}

The Terminal never prints "Hello User". Also, no other signals are being printed. By removing the if-condition, I get a whole lot of "Hello User" and "-1" in the Arduino IDE serial monitor.

Concerning my setup:

I've got an USB to Serial converter, which is connected as "COM3". On the other side, I have an Arduino UNO which is connected via USB to the same computer. The TX pin of the converter is connected to the RX pin of the Arduino and vice versa. Also, Ground is connected to Ground. Furthermore, I use Jupyter/IPython notebook to run my Python script, and the default Arduino IDE to compile programs for my Arduino. In the case there I received data from the Arduino, I used the script specified in the URL provided, which is very similar to the one I'm already showing here. Also, ser.write() is replaced by ser.read(1), so that it reads one byte at a time. My system is Windows 7 (64 Bit).

Edit: Here is an established connection between hTerm (a serial terminal) and the Python script while using com0com as a port emulator.


texts:
#include <DS3231.h>
#include <Wire.h>  // i2C Conection Library

// Init DS3231
DS3231  rtc;
// Init a Time-data structure
Time  t;
uint32_t targetTime = 0;

uint8_t hh = 0, mm = 0, ss = 0, dd = 0, bb = 0; //variable Unsignet int 0-255
int yy = 0; //variable integer
String Day = "  "; //variable string

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

void loop() {
  t = rtc.getTime(); // gate all data time & date from RTC
  Day = rtc.getDOWStr(); //get name of day
  hh = t.hour,DEC; //pengambilan data jam
  mm = t.min,DEC; //pengambilan data menit
  ss = t.sec,DEC; //pengambilan data detik
  dd = t.date,DEC; //pengambilan data hari
  bb = t.mon,DEC; //pengambilan data bulan (dalam desimal)
  yy = t.year,DEC; //pengambilan data tahun
  //Buka Serial Monitor Arduino untuk melihat hasilnya
  Serial.print (Day);
  Serial.print (F(" Time = "));
  Serial.print (hh); Serial.print (F(" : "));
  Serial.print (mm); Serial.print (F(" : "));
  Serial.print (ss); Serial.print (F("  Date = "));
  Serial.print (dd); Serial.print (F(" . "));
  Serial.print (bb); Serial.print (F(" . "));
  Serial.println (yy);
  delay (1000);
}

When I verify the code, this error appears:

  exit status 1
  'Time' does not name a type

What does it mean?


texts: I'm looking for a counter that can be incremented and will overflow with predictable behavior, preferably reset to 0 on overflow. I've tried using integers for counting but I'm getting weird overflow issues. Is there some library that provides an implementation of a counter?


texts:
What power source should I use for my Arduino Mega project (involves 2 steppers, 2 servos and 2 dc motors)?

I tried to run two stepper motors with 9V battery. But the battery dried out. I am thinking of 8 AAA batteries. Is there a better option? How about powering through Arduino with the help of a DC adapter?


texts: ADC pin shutting off on its own under certain condition

texts:
A0 pin not working when full PV system in use

I am using the DFRobot Leonardo with Xbee R3. I am using the A0 pin to read a 0-5V voltage from my voltage sensor, which samples and steps down 130VDC from a solar panel, in parallel to 0-5V for my Arduino to read.

Album with all relevant images

PV Array is 7 Panels in Series, Vpeak 18.7V Apeak: 11.23A

When the PV system is in open circuit mode (not connected to the grid), A0 can read the voltage without any issues and output's it into my serial monitor.
When the PV system is connected to the grid, A0 seemly shut's itself off and i no longer get any serial output. Testing with multimeter shows that the A0 pin is still getting a voltage in the range of 0-5V.

My assumption is that when a load is applied to the system, either A0 shuts itself down to protect the board for some reason, or the current is not flowing through the voltage sensing circuit due to it's higher resistance.

Current sensor is a 0-20A ACS712 board.


texts:
So I am trying to use one input to control an LCD display. The goal being that once one of the buttons is pressed it delivers a message. I have watched quite a few tutorials and can get the program to work sometimes. Yet, it is still pretty buggy and I am wondering why that is. To get this make this project work somewhat used this code.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int buttonPin = A0;     //Button and LED pin numbers
    void setup()
{
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  //lcd.print("hello, world!");
  Serial.begin(9600);           //Serial monitor used to determine limit values

 }

void loop()
{
  int temp = analogRead(buttonPin);   //Read the analogue input
  Serial.println(temp);               //Display the read value in the Serial monitor
  if (temp = 340)                     //Lower limit for first button - if below this limit then no button is pushed and LEDs are turned off
  {
  lcd.print("No Button Pushed \n");
  }
  else if (temp = 867)                //First button limit - if below this limit but above previous limit then the first button is pressed
  {
    lcd.print("Button 1 Pushed");
  }
  else if (temp = 156 )                //Second button limit
  {
    lcd.print("Button 2 Pushed");
  }

  else                                //If none of the previous buttons are pressed, then the third button must be pressed
  {
    lcd.print("Button 3 Pushed");
  }
  delay(100);                         //Delay for stability
}

The output sometimes is correct other times it is off. I think it has something to do with the circuit. Yet, I am scratching my head to find out what.


texts: Can I power an Arduino with a computer's motherboard?

texts:
I was thinking of using my Arduino to turn on and off a computer remotely. I would like to know if the 5v header pin on a computer's motherboard (which I’m using instead of a USB because the 5v pin provides a constant power supply) can power an Arduino UNO without frying it. If the Arduino can be powered where would the cable from the 5v motherboard pin go into the Arduino?

↑ These are the pins I would like to use


texts: DMX on the Arduino without additional driver chip

texts:
I recently saw this video where the creator controlled a DMX light via the Arduino. There he used the pins 3 and 4 for the data on the Arduino Duemilanove. As DMX library he used DmxSimple.

Based on my research DMX is RS-485 and for this there's a driver chip required.

So I have three questions about this:

Why do all sources I found say that there's a driver chip required when it seems to work without?
I got a Arduino Leonardo compatible device (Devduino). Is it possible to control DMX like stated above on this platform?


texts:
What is the shortest/most elegant way (i.e. use existing lib functions) to parse a string in the form of 20180810T143000Z to a time_t? Note that the literal always represents a UTC timestamp.

I started parsing the string and assigning values to a struct tm *tm in order to do a mktime(tm) at the end. That feels overly complicated, though.


texts: Programming ATUC256L4U using only Arduino ISP

texts: I heard that you can program any AVR Microcontroller by just using Arduino ISP Can I program ATUC256L4U by just hooking it up to Arduino ISP and Caps, Crystals and etc. Or do I need to do some more work like you know the fuses and all ?


texts:
i'm using ModbusMaster library (Repo) to read from a device some registers.

Many of them are float and i've no problem to read them using the following code:

  //for float conversation
  union
    {
      uint32_t i;
      float f;
    }u;
    uint8_t result = node.readInputRegisters(address, 2); // for 3000xx registers
    Serial.println("Result : " + String(result));// to get error type
    if (result == node.ku8MBSuccess)
    {
         u.i=(((unsigned long)node.getResponseBuffer(0x01)<<16) | (node.getResponseBuffer(0x00)));// shifting 2nd register to left & stiching with 1st register
    }
    Serial.println("Reading is "+String(u.f));

But i have the energy registers that are 64 Bit unsigned int and i can't figure out how to adapt the above code in order to read them.

Anyone has a solution?


texts: Alternative to patching core library source and header files

texts: I am following a DIY guide that requires me to patch two arduino core library files: HID.cpp and USBAPI.h. This is not really practical for many reasons. I am not a native C programmer, but I am sure there are better ways to achieve the same without messing directly with system files. How can I override system library files without modifying the originals?


texts: Digital map in A* search algorithm in Arduino

texts:
I am building an Automated Guided Vehicle as my graduation project. I'm new to path-finding algorithms and I've only worked with small projects based on Arduino as of now.
I've chosen A* search after careful understanding of many other algorithms (Dijkstra's/D*, etc.) and using Arduino Uno (will switch to Due later) for the robot.

I've implemented the code for A* in C++ as well.

But I've got stuck in its implementation in Arduino. I don't know how to create a digital map of the arena (I'm using a 4 sq.m area and using a 10X10 grid for it). I don't have any idea how to move the robot in that arena with the digital map (I reckon I'll need wheel encoders and an ultrasonic sensor mounted on a servo for orientation).

My main problem is creating a digital map of the arena and how to go about it.

I'm attaching a code for A* for reference and the grid used in it.

// Driver program to test above function
int main()
{
  //* Description of the Grid-
   1--> The cell is not blocked
   0--> The cell is blocked    *//
  int grid[ROW][COL] =
  {
    { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
    { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },
    { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
    { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 },
    { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
    { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
    { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },
    { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
    { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 }
  };

  // Source is the left-most bottom-most corner
  Pair src = make_pair(8, 0);

  // Destination is the left-most top-most corner
  Pair dest = make_pair(0, 0);

  aStarSearch(grid, src, dest);

  return(0);
}


texts: Can I connect an SD card shield to Digispark ATtiny85 board?

texts: I have a Digispark ATtiny85 Arduino board (as shown in the picture). Can I connect a SD card shield to this board as a normal Arduino? How can I do that I'm new to this field?


texts:
I am trying to find a simple timer0 interrupt example, but none of those work. Neither this code which I tried to run:

boolean toggle0 =0;

void setup() {
pinMode(8, OUTPUT);
  cli();

  // Set timer1 interrupt at 1 Hz
  TCCR1A = 0; // Set entire TCCR1A register to 0
  TCCR1B = 0; // Same for TCCR1B
  TCNT1  = 0; // Initialize counter value to 0

  // Set compare match register for 1 Hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)

  // Turn on CTC mode
  TCCR1B |= (1 << WGM12);

  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);

  // Enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  sei();
}

ISR(TIMER0_COMPA_vect){  // Change the 0 to 1 for timer1 and 2 for timer2
  if (toggle0){
    digitalWrite(8,HIGH);
    toggle0 = 0;
  }
  else{
    digitalWrite(8,LOW);
    toggle0 = 1;
  }
}

void loop() {

}

What am I doing wrong?


texts:
When I do

myServo.write(0)

It isn't straight, I want it to be straight but it is at about a 45 degree angle anyone know how to reset the position with arduino to make other positions 0 and making everything relative to where that zero is?


texts: Arduino Leonardo as keyboard for an iPad

texts:
I'm trying to make a Arduino Leonardo as a Keyboard for an iPad. I was successful with an Arduino UNO. However I'm hoping to use an ATmega 32U4 because of the better HID functionalities and smaller boards like the Beetle.

The problem I'm having is that when I connect the Leonardo to my iPad, the iPad shows an alert saying that the Leonardo is using too much power.

Tried running the board with an external power source. Then I get a different alert: Device not Supported.

At this point I believe that the problem is not necessarily power, but the fact that the Leonardo is announcing itself to the iPad and the iPad does not like it. In the UNO project, through re-flashing, the board acts only as a HID.

Is there a way to make the Leonardo (or other ATmega 32U4 based board) to not advertise itself on the USB port while allowing the HID functionality to operate?


texts: Save data from an LCD KeyPad Shield to an sd card

texts:
I'm developing a project that requires save data from a sensor that is connected in a LCD keypad shield, the information should be save in a file into SD card.

My code

#include <LiquidCrystal.h>
#include <SD.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int buttons;
File myFile;
//name of the file
char nombrefichero[12];
int i = 1;
int exist = LOW ;

void setup() {
Serial.begin(9600);
//check the sd card adapter
  Serial.print("Iniciando SD ...");
  if (!SD.begin(53)) {
    Serial.println("No se pudo inicializar");
    return;
  }
  Serial.println("inicializacion exitosa");
}

void loop() {
// use the buttons of the lcd keypand shield in analog 0
buttons = analogRead(0);

//button right
if(buttons < 50){
  count ++;
  nuevo();
}

//button select
if(buttons < 790){
  capturar();
}

}

void capturar(){
  myFile = SD.open(nombrefichero, FILE_WRITE);//abrimos  el archivo

  if (myFile) {
        Serial.print("Escribiendo SD: ");
        int sensor1 = analogRead(0);
        int sensor2 = analogRead(1);
        int sensor3 = analogRead(2);
        myFile.print(millis());
        myFile.print(",");
        myFile.print(sensor1);
        myFile.print(",");
        myFile.print(sensor2);
        myFile.print(",");
        myFile.println(sensor3);

        myFile.close(); //cerramos el archivo

        Serial.print("Tiempo(ms)=");
        Serial.print(millis());
        Serial.print(",sensor1=");
        Serial.print(sensor1);
        Serial.print(",sensor2=");
        Serial.print(sensor2);
        Serial.print(",sensor3=");
        Serial.println(sensor3);

  } else {
    // if the file didn't open, print an error:
    Serial.println("Error al abrir el archivo");
  }
  delay(1000);
}

void nuevo(){

while (exist == LOW)
  {
    sprintf(nombrefichero, "M%d.txt",i); //generate autoincrement number of
file

    if(SD.exists(nombrefichero))
    {
       i = i+1;
      myFile = SD.open(nombrefichero, FILE_WRITE);
      if (myFile) {
        Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)");
        myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3");

        myFile.close();

      } else {
        exist = HIGH;
        Serial.println("Error creando el archivo");
      }
  }

  }
}

I need capture the information of the sensor when I pressed the select button and when the right button is press create a new file in this method, in this line if(SD.exists(nombrefichero)) if I put the ! before SD.exist the files are created infinite but if I leave it as is without the ! the button does nothing

void nuevo(){

while (exist == LOW)
  {
    sprintf(nombrefichero, "M%d.txt",i);
    if(SD.exists(nombrefichero))
    {
       i = i+1;
      myFile = SD.open(nombrefichero, FILE_WRITE);
      if (myFile) {
        Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)");
        myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3");

        myFile.close();

      } else {
        exist = HIGH;
        Serial.println("Error creando el archivo");
      }
  }

  }
}

I'm use arduino mega 2560 and SD card Adapter


texts: Hardware interrupts for buttons not directly assigned to pins

texts:
The Adafruit LCD shield offers an LCD and access to 4 button, using only a two wire connection with the Arduino.
This is achieved with the MCP23017 I2C port expander IC.

These buttons are not directly assigned to pins, since only two pins are required for the whole communication, via the I2C protocol.

Can i use a hardware interrupt with any of the 4 buttons?
If not, is there any workaround to trigger an interrupt when one of these buttons is pressed?

PS: I am using Arduino Due


texts: Newbie trying to interface MLX90614 with Arduino Due

texts:
Im a newbie and Im trying to interface the temperature sensor mlx90614 to the arduino due using i2c bus. After a lot of digging I found this code which works,but it works only on the sda(20),scl(21) pins. I want to change this to SCL1 and SDA1 near the Aref and gnd pins. How do i modify this code? Thanks

#include <Arduino.h>
#include <include/twi.h>

#define ADDR      0x5A

//EEPROM 32x16
#define TO_MAX    0x00
#define TO_MIN    0x01
#define PWM_CTRL  0x02

//RAM 32x16
#define RAW_IR_1  0x04
#define RAW_IR_2  0x05
#define TA        0x06
#define TOBJ_1    0x07
#define TOBJ_2    0x08

#define SYNC_PIN  2

static const uint32_t TWI_CLOCK = 100000;
static const uint32_t RECV_TIMEOUT = 100000;
static const uint32_t XMIT_TIMEOUT = 100000;

Twi *pTwi = WIRE_INTERFACE;

static void Wire_Init(void) {
  pmc_enable_periph_clk(WIRE_INTERFACE_ID);
  PIO_Configure(
  g_APinDescription[PIN_WIRE_SDA].pPort,
  g_APinDescription[PIN_WIRE_SDA].ulPinType,
  g_APinDescription[PIN_WIRE_SDA].ulPin,
  g_APinDescription[PIN_WIRE_SDA].ulPinConfiguration);
  PIO_Configure(
  g_APinDescription[PIN_WIRE_SCL].pPort,
  g_APinDescription[PIN_WIRE_SCL].ulPinType,
  g_APinDescription[PIN_WIRE_SCL].ulPin,
  g_APinDescription[PIN_WIRE_SCL].ulPinConfiguration);

  NVIC_DisableIRQ(TWI1_IRQn);
  NVIC_ClearPendingIRQ(TWI1_IRQn);
  NVIC_SetPriority(TWI1_IRQn, 0);
  NVIC_EnableIRQ(TWI1_IRQn);
}

static void Wire1_Init(void) {
    pmc_enable_periph_clk(WIRE1_INTERFACE_ID);
  PIO_Configure(
      g_APinDescription[PIN_WIRE1_SDA].pPort,
      g_APinDescription[PIN_WIRE1_SDA].ulPinType,
      g_APinDescription[PIN_WIRE1_SDA].ulPin,
      g_APinDescription[PIN_WIRE1_SDA].ulPinConfiguration);
  PIO_Configure(
      g_APinDescription[PIN_WIRE1_SCL].pPort,
      g_APinDescription[PIN_WIRE1_SCL].ulPinType,
      g_APinDescription[PIN_WIRE1_SCL].ulPin,
      g_APinDescription[PIN_WIRE1_SCL].ulPinConfiguration);

  NVIC_DisableIRQ(TWI0_IRQn);
  NVIC_ClearPendingIRQ(TWI0_IRQn);
  NVIC_SetPriority(TWI0_IRQn, 0);
  NVIC_EnableIRQ(TWI0_IRQn);
}

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

  pinMode(SYNC_PIN, OUTPUT);
  digitalWrite(SYNC_PIN, LOW);

  Wire_Init();
  // Disable PDC channel
  pTwi->TWI_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS;
  TWI_ConfigureMaster(pTwi, TWI_CLOCK, VARIANT_MCK);
}

void loop() {
  uint16_t tempUK;
  float tempK;
  uint8_t hB, lB, pec;

  digitalWrite(SYNC_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(SYNC_PIN, LOW);

  TWI_StartRead(pTwi, ADDR, TOBJ_1, 1);

  lB = readByte();
  hB = readByte();

  //last read
  TWI_SendSTOPCondition(pTwi);
  pec = readByte();

  while (!TWI_TransferComplete(pTwi))
    ;
  //TWI_WaitTransferComplete(pTwi, RECV_TIMEOUT);

  tempUK = (hB << 8) | lB;
  if(tempUK & (1 << 16))
  {
    Serial.print("Error !");
    Serial.println(tempK);
  }
  else
  {
    tempK = ((float)tempUK * 2) / 100 ;
    //Serial.print("Temp UK: ");
    //Serial.print(tempUK);
    Serial.print(" C: ");
    Serial.println(tempK - 273.15);
  }
  //Serial.print(hB, HEX);
  //Serial.print(" : ");
  //Serial.print(lB, HEX);
  //Serial.print(" : ");
  //Serial.println(pec, HEX);

  delay(2000);
}

uint8_t readByte() {
  //TWI_WaitByteReceived(pTwi, RECV_TIMEOUT);
  while (!TWI_ByteReceived(pTwi))
    ;
  return TWI_ReadByte(pTwi);
}

static inline bool TWI_WaitTransferComplete(Twi *_twi, uint32_t _timeout) {
  while (!TWI_TransferComplete(_twi)) {
    if (TWI_FailedAcknowledge(_twi))
      return false;
    if (--_timeout == 0)
      return false;
  }
  return true;
}

static inline bool TWI_WaitByteReceived(Twi *_twi, uint32_t _timeout) {
  while (!TWI_ByteReceived(_twi)) {
    if (TWI_FailedAcknowledge(_twi))
      return false;
    if (--_timeout == 0)
      return false;
  }
  return true;
}

static inline bool TWI_FailedAcknowledge(Twi *pTwi) {
  return pTwi->TWI_SR & TWI_SR_NACK;
}


texts: ATmega 2560 with Arduino bootloader running issue

texts:
I have designed a board based on an ATmega2560 chip and I burned the bootloader by following this tutorial.

Now I am able to load Blinky and other programs using an FTDI cable. But the issue I am facing right now is the controller runs Blinky fine if I leave the FTDI connected there. If I disconnect the FTDI cable and power-cycle the board it is not running Blinky. If I connect the FTDI, right away it starts blinking.

It looks like something is wrong with my RESET pin connection? Here is what my RESET circuitry looks like:

I also have tried by removing D1 diode but no luck !


texts:
Hi i am using ESP8266EX along with Arduino Due rev3 to check wifi status. when i compile my following sketch compiler give me error
User\Awais\Document\Arduino\liberaries\espsoftserialmaster\softserial.cpp:27:18: fatal error: gpio.h: no file or directory found
any one help me solve this problem

    #include <SoftwareSerial.h>
    SoftwareSerial ESPserial (15,14); //RX|TX

     void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  ESPserial.begin(115200);
  Serial.println("NL & CR");
}

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

  if (ESPserial.available()){
   Serial.write(ESPserial.read());
  }

if (Serial.available()){
ESPserial.write(Serial.read());
}
  }


texts: How to access variables by variable? (I.e. variable variables?)

texts:
Can Arduino handle variable variables?

function getLetterCode(char input) {
    int letter_a = 17;
    int letter_b = 42;
    int letter_c = 50;
    return letter_$$input$$; //pseudocode
}

This is just a stripped down code to demonstrate my question. I am aware of arrays, the switch structure and other workarounds, but for my specific need variable variables would save tons of typing.


texts: Unable to understand the acquisition of data from Magnetometer HMC5883L and Accelerometer ADXL345

texts:
Below are the X,Y,Z registers for HMC5883L.

while this is the Arduino code for HMC5883L to acquire X,Y,Z reading.
If you look at this code, we do not mention the X, Y, Z address specifically.

  Wire.beginTransmission(0x1E);
  Wire.write(0x02);
  Wire.write(0b00000001);
  Wire.endTransmission();
  delay(10);

  Wire.requestFrom(0x1E,6);
  if (Wire.available() > 5)
  {
    x = readValue();
    y = readValue();
    z = readValue();
  }
  else
  {
    Serial.println("No data found");
  }
int readValue()
{
  int val = Wire.read()<<8;
      val |= Wire.read();

  return val;
}

We only write Wire.request() and do not mention X,Y,Z addresses specifically for HMC5883L.
While in the case of ADXL345 we mention every register of X,Y,Z separately to acquire data. Which is exactly my question like why not simply use Wire.requestFrom() for ADXL345 too. When will we access each X,Y,Z register separately? and when will we do not?

Below is Arduino ADXL345 code for reading X axis data.

  Wire.beginTransmission(0x53);
  //Ask the particular registers for data
  Wire.write(0x32);
  Wire.write(0x33);
  Wire.endTransmission();
  Wire.requestFrom(0x53,2);
  if(Wire.available()<=2) {
    X0 = Wire.read();
    X1 = Wire.read();
    X1=X1<<8;
    X_out =X0+X1;
    Xa=X_out/256.0;
  }

Datasheets for both sensors are available on the link.

The code above is not mine.
https://drive.google.com/open?id=1AswNTdBz55Rfg3nu4-YsLFj4ANrsCL5I


texts:
I have a PPD42NS dust sensor I'd like to hook up to an ESP8266-01 microcontroller. The ESP8266 uses 3.3v logic, but the PPD42NS uses 5v. The PPD42NS uses low pulse occupancy as output.

I'd like to use parts I have on hand, and I was wondering if a simple voltage divider built from 2 resistors can reliably shift the voltage without distorting the signal.

If not, could an NPN transistor do the job instead?


texts:
I purchased these slide switches recently because I want to use them in my project:

But I don't know what to connect up the three pins to and I can't find any information about them online. Nor can I find sample code. Can someone show me how to wire them up and provide sample code please? I just want to be able to check their state and save it as a boolean variable.


texts: Adding bootloader to Feather M0 Bluefruit LE

texts:
I want to make a custom Feather M0 Bluefruit LE. I know this means that I will have to add a bootloader to the ATSAMD21G18.

I have seen that there are many useful articles in relation to adding bootloader to this chip like

https://www.instructables.com/id/ATSAMD21g18-Bootloader-With-J-link-Debugger/

and

https://learn.adafruit.com/proper-step-debugging-atsamd21-arduino-zero-m0/restoring-bootloader

and

https://learn.adafruit.com/compiling-m0-atsamd21-bootloader/compile

I wanted to make sure that the bootloader will allow me to access the Bluetooth module on the board. Does anyone know if this bootloader will do that? Or is there another type of bootloader I need? Also, do I need a J-link connection on the custom board? can I just use USB?


texts: Serial port /dev/cu.usbmodemfa131 vs /dev/cu.usbserial-A702NY8S

texts:
On Mac OSX Mavericks, why does Arduino Uno uses serial port named /dev/cu.usbmodemfa131 while Arduino Nano uses /dev/cu.usbserial-A702NY8S?

Are they using different FTDI drivers?


texts:
So I have a Bunch of commonly used char arrays to build commands in my library.
So to preserve memory, I have them put into flash, via PROGMEM ext,

typedef const char PROGMEM ProgChar;
ProgChar AT[] = "AT";
ProgChar AT_RST[] = "RST";

Then in my program I have it all go out to A port via:

*hws << AT << PLUS << CWMODE << EQUAL; //hws can be any Print type,

This is handled by overloading the << operator;

static Print &operator <<(Print &obj, ProgChar* arg) {
  char pbuffbuffer[12]; //create a buffer,
  obj.print(loadProgmemVal(arg,pbuffbuffer)); //Load it, and then pass to obj print method.
  return obj;
}

But this also overloads the << operator for all const char* Which makes me have to do a workaround:

hws->print(1); //HACK

At first, I thought I would overload the operator to handle both a char* and a Prog Char Object, But unfortunately, they are both treated as the same thing at run-time which makes that idea useless.

So after snooping I find the __FlashStringHelper type and macro. Which would allow me to have a sepperate type for these variables, and allow me to overload.

But the problem is, I cant find a good way to Create these:

const __FlashStringHelper MYVAR = F("Some text to be progchared");

Does not compile =/

Now I could probably make some helper method to load them all in, but that is just patching a hack with another hack... Is there any Clean way to do this? So I can use << for all types,

*hws << AT << PLUS << CWMODE << EQUAL << 1 << "\r\n"; //1 and Return break...


texts: Why doesn't my code work in a function, yet works inline?

texts:
I'm trying to write a faster shiftOut function, which does not use the slow digitalWrite. In my code I have the original shiftOut, the new shiftOutFast, and the same as shiftOutFast, but inline. The three blocks are separated by delays to tell them apart on my scope. Here's the code:

#define CLR(x,y) (x &= (~(1 << y)) )
#define SET(x,y) (x |= (1 << y) )

void shiftOutFast(uint8_t dataPort, uint8_t dataBit, uint8_t clkPort,
                  uint8_t clkBit, uint8_t bitOrder, uint8_t val) {
  for (uint8_t i = 0; i < 8; i++)  {
    if (bitOrder == LSBFIRST) {
      if (val & 0x01) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val >>= 1;
    } else {
      if (val & 0x80) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val <<= 1;
    }

    CLR(clkPort, clkBit);
    SET(clkPort, clkBit);
  }
}

#define dataPin 4
#define clockPin 5
#define dataPort PORTD
#define dataBit PORTD4
#define clockPort PORTD
#define clockBit PORTD5

void setup() {
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop() {
  shiftOut(dataPin, clockPin, LSBFIRST, 0x55);
  delay(1);

  shiftOutFast(dataPort, dataBit, clockPort, clockBit, LSBFIRST, 0x5C);
  delay(1);

  bool bitOrder = LSBFIRST;
  uint8_t val = 0x5C;

  for (uint8_t i = 0; i < 8; i++)  {
    if (bitOrder == LSBFIRST) {
      if (val & 0x01) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val >>= 1;
    } else {
      if (val & 0x80) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val <<= 1;
    }

    CLR(clockPort, clockBit);
    SET(clockPort, clockBit);
  }
  delay(1);
}

The problem is that calling shiftOutFast doesn't do zilch. Absolutely nothing. It doesn't seem to be the logic, because when I do the same inline it works. Any ideas?


texts:
It might be an obvious answer to this, but I can't find it via a quick google search. To give my question a bit of more context, I'm writing an application which simulates a communication with Arduino via serial port, therefore I need to know how it is implemented internally.

From my previous experience with micro-controllers, the serial port is normally presented in micro-controller as two separate queues, one for TX and another for RX. For transmit out of MC, my software writes a byte to the end of transmit queue, and MC hardware reads byte from the beginning of the queue, converts it to bits, and toggles the pin to transmit data/parity/stop bits. And it keep doing that until queue is exhausted. The opposite happens for receive queue.

Am I right in assuming that Arduino has similar implementation with two separate queues? In particular, I want to read and write to serial port simultaneously.


texts: How to reset an arduino while being able to know which button has been pressed?

texts:
Context

I keep the board in sleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot.

In the following schematic, SW-R is actually used to reset the board.

If I hold SW-D5 or SW-D6 while pushing SW-R, the code can detect which button I pushed.

Problem

I don't want to have to push 2 buttons at the same time and, being new to electronic, I don't know how to wires things up so it reset and set a pin to HIGH simultaneously.

Question

How can I reset the board and trigger a HIGH on an IO corresponding to a button while it boot?

Considering the HIGH only need to be hold for less than a second, can it be simply achieved with capacitors and/or transistors? If so, how? Or any other suggestion?

simulate this circuit – Schematic created using CircuitLab

The actual code example only contain 1 button but I'll have many.

#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);

  int buttonValueAtBoot = digitalRead(buttonPin);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == HIGH) {
    // I want to trigger this code pushing only 1 button
    // should also work with many buttons
    Serial.println("button was pressed");
  }

  digitalWrite(BUILTIN_LED, HIGH);
}

void loop() {
  delay(5000);
  ESP.deepSleep(0);
}


texts: changing from long to bytes and vice versa

texts:
I want to converse data from long to bytes and vice versa. After searching around, I sticked together some code, which seems to work (the same code works for int and floats as well).

The long value LongVal changes to a byte array, and the four bytes construct LongVal2. Obviously LongVal = LongVal2.

long LongVal = -4080;
long LongVal2;

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

//byte* my_function(long LongVal){
//  byte *LongVal_byte = (byte *) & LongVal;
//  return & (LongVal_byte[0]);
//}

//long my_function2(byte & LongVal_byte){
//  long LongVal2;
//  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
//  return  LongVal2;
//}

void loop(){

  byte *LongVal_byte = (byte *) & LongVal;
  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
  Serial.println(LongVal2);
  Serial.println(" ");

//byte LongVal_byte = my_function(long LongVal);
//LongVal2 = my_function2(byte & LongVal_byte);

}

But should I try to wrap the two first lines of loop() in two individual functions, errors occur. The remarked lines are my attempts to create two functions.

How to wrap them up properly?

EDIT
This is what appears if I try to use the remarked functions:

 In function 'long int my_function2(byte&)':
15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void*' [-fpermissive]
25:0,
1:
117:14: error:   initializing argument 2 of 'void* memcpy(void*, const void*, size_t)' [-fpermissive]

 In function 'void loop()':
26:33: error: expected primary-expression before 'long'
27:30: error: expected primary-expression before '&' token


texts:
Using LabVIEW I am sending string of data through Xbee like,

u123
r64
r89
u34
r179

And my arduino is receiving this data.
I want my arduino to read this data as a string
and I want to extract numbers from these strings and feed it into two different servos.
For example from u123 I want to extract 123 and feed it to servo1 and from r64 I want to extract 64 and feed it to servo2 and so on.

Arduino IDE Serial Monitor is showing nothing but Arduino's Xbee is receiving and sending data. Don't know why :(


texts:
I am having a problem. I designed obstacle robot with ultrasonic sensor. But the problem i'm facing is one that no one discussed ever. I kept on searching it on internet and found no solution for it. So, i decided to ask it here:

Firstly, I used one ultrasonic sensor to avoid obstacle alongwith servo motor using newping library. But it failed badly due to an elevation of the sensor so it doesn't detect any lower height object.

Second time, i used three ultrasonic sensors to check for the side's obstacles and front obstacle as well. In most of the cases what no one ever showed in video there are some places and times when it get stuck (due to design and even sonar limitation).

What i want to do is to add some features to the code that can detect stuck motor or stopped robot at one place. Once detected this condition it moves backward and turn the other way if again stuck then move backward and turn the other way.

I hope i could make you understand the problem i'm facing. I'll appreciate the solution and it may help others to find solution for it. I don't know how to attach the code here (it may create mess for the reader). So, please tell me if i need to send or attach here. Thanks.!


texts:
I have the following situation:

One Arduino Uno with a 433mhz transmitter wired to the laptop to have serial communication. Another Arduino Uno with a 9V battery wired with a 433mhz receiver and an LCD screen (16x2, I2C).

I have the following code to transmit:

#include <VirtualWire.h>

void setup() {
  //Force low when enabled
  vw_set_ptt_inverted(true);
  //Set pin 12 for transmitter
  vw_set_tx_pin(12);
  //Setup with speed of the data transfer.
  vw_setup(4000);
  //Set serial communication at 9600 baud
  Serial.begin(9600);//set Serial
  //Set pin 13 to light up when transmitting
  pinMode(13,OUTPUT);
}

void loop() {
  //If message send via serial monitor
  if (Serial.available()) {
    //wait a bit for the entire message to arrive
    delay(100);

    while (Serial.available() > 0) {
      //Read serial into string
      String message = Serial.readString();
      //Initialize char array
      char msg[message.length()];
      //Write string to char array
      message.toCharArray(msg, message.length());
      //send char array as unsigned int (bits)
      vw_send((uint8_t *)msg, strlen(msg));
      //Wait until the complete message has been send
      vw_wait_tx();
      //Turn on light when finished
      digitalWrite(13,HIGH);
      delay(200);
    }
  }else{
    //Turn off light
    digitalWrite(13, LOW);
  }
}

And the following code to receive a message and print on a LCD screen:

#include <LiquidCrystal_I2C.h>
#include <VirtualWire.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

void setup() {
  //start up LCD with 16 chars with 2 lines
  lcd.begin(16,2);
  //Turn on backlight
  lcd.backlight();
  //Write initialising message
  lcd.setCursor(0,0);
  lcd.print("Initialisation..");
  //Force low when enabled
  vw_set_ptt_inverted(true);
  //Set pin 12 to receive
  vw_set_rx_pin(12);
  //Setup with speed of the data transfer.
  vw_setup(4000);
  //set pin 13 for light
  pinMode(13, OUTPUT);
  //Start receiver
  vw_rx_start();

  //Set message on LCD that setup has completed
  lcd.setCursor(0,1);
  lcd.print("Completed!");
}

void loop() {
  //initialize array for message
  uint8_t msg[VW_MAX_MESSAGE_LEN];
  uint8_t msgLength = VW_MAX_MESSAGE_LEN;

  //If message received
  if (vw_get_message(msg, &msgLength)){
    //Turn on light
    digitalWrite(13, HIGH);

    //Print on lcd
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.write(msg, msgLength);
  }else{
    //Else turn of light
    digitalWrite(13, LOW);
  }
}

My problem is that the message that is being transmitted and received by the other arduino always is short 1 character. For example if I send "test", it receives and displays "tes". What am I missing?

(My short solution was to just add a space to the message, then the space got cut off. But I want to understand what is going wrong.)


texts:
Controlling speed of DC Motor from arduino could be done via PWM and H-Bridge, but how can i control an AC Motor?
Thank you.


texts: Arduino IDE not handling library code correctly?

texts:
The author of the PinChangeInt library and the EnableInterrupt library states at github:

  When the PinChangeInt was in a .h and .cpp file, the Arduino IDE tried
  to compile it twice. I have a technique that you can use- #define
  LIBCALL_ENABLEINTERRUPT - that if you put it ahead of your #include in
  all files but the sketch, then you should be able to use the library
  without conflicts. If you know how to make it work in another way-
  remember, this is a library and will not compile in the same directory
  as the sketch and any other .h/.cpp/.ino files- then I'm all ears.

I came there, because both libraries failed to build with linker errors due to double definitions. So far so good. I split the PinChangeInt library in .h and .cpp myself and it compiled flawlessly. I did not try to split the other library yet because it looks like much work to me.

So now my question(s): Is GreyGnome right with his statement, that library code gets compiled twice when split in code and headers? And if so, what are the consequences? Memory waste? Runtime errors? What about the many other (working) libraries exhibiting separate code and header files?


texts: that no matter what the inputs are Motor1 always moves

texts:
int motor_forward1 = 7;
int motor_reverse1 = 6;
int motor_forward2 = 5;
int motor_reverse2 = 4;
int motor_forward3 = 3;
int motor_reverse3 = 2;
int sensor1 = A0;
int sensor2 = A1;

 void setup()
{

   pinMode(motor_forward1, OUTPUT);
   pinMode(motor_reverse1, OUTPUT);
   pinMode(motor_forward2, OUTPUT);
   pinMode(motor_reverse2, OUTPUT);
   pinMode(motor_forward3, OUTPUT);
   pinMode(motor_reverse3, OUTPUT);
   pinMode(sensor1, INPUT);
   pinMode(sensor2, INPUT);
 }

 void loop()
 {
   if (digitalRead(A0) == HIGH)
   {
     digitalWrite(motor_forward1,1);
     digitalWrite(motor_reverse1,0);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,1);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,0);
     delay(1000);
   }
   else if (digitalRead(A1) == HIGH)
   {
     digitalWrite(motor_forward2,1);
     digitalWrite(motor_reverse2,0);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,1);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,0);
     delay(1000);
   }
   else
   {
     digitalWrite(motor_forward3,1);
     digitalWrite(motor_reverse3,0);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,1);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,0);
     delay(1000);
   }
   delay(5000);
 }

Schematic here.


texts: Please help. Error message “sendSMS not declared in this scope” im frustrated. :(

texts:
//INCLUDED LIBRARIES
 #include <GPRS_Shield_Arduino.h>
#include <SoftwareSerial.h>
#include <Wire.h>

//SERIAL PIN ASSIGNMENT, BAUDRATE, PHONE NUMBER, MESSAGE
#define PIN_TX    2
#define PIN_RX    3
#define BAUDRATE  9600
#define PHONE_NUMBER "+639158848570"       //CELLPHONE NUMBER
#define MESSAGE  "Notice: Please be informed that your area is under Level 1 advisory with 4-inches flood depth. Continuous flood is expected due to the heavy rainfall. Be prepared and secure your important documents and belongings in high places. Avoid wirings from getting wet to prevent further injuries and accidents."  //COMPOSE YOUR MESSAGE HERE
#define MESSAGE_LENGTH <=500
char MESSAGE1;

//SERIAL PIN ASSIGNMENT, BAUDRATE, PHONE NUMBER, MESSAGE
#define PIN_TX    2
#define PIN_RX    3
#define BAUDRATE  9600
#define PHONE_NUMBER "+639379488989"       //CELLPHONE NUMBER
#define MESSAGE  "Notice: Please be informed that your area is under Level 1 advisory with 4-inches flood depth. Continuous flood is expected due to the heavy rainfall. Be prepared and secure your important documents and belongings in high places. Avoid wirings from getting wet to prevent further injuries and accidents."  //COMPOSE YOUR MESSAGE HERE
#define MESSAGE_LENGTH <=500
char MESSAGE2;

//SERIAL PIN ASSIGNMENT, BAUDRATE, PHONE NUMBER, MESSAGE
#define PIN_TX    2
#define PIN_RX    3
#define BAUDRATE  9600
#define PHONE_NUMBER "+639357120147"       //CELLPHONE NUMBER
#define MESSAGE  "Notice: Please be informed that your area is under Level 1 advisory with 4-inches flood depth. Continuous flood is expected due to the heavy rainfall. Be prepared and secure your important documents and belongings in high places. Avoid wirings from getting wet to prevent further injuries and accidents."  //COMPOSE YOUR MESSAGE HERE
#define MESSAGE_LENGTH <=500
char MESSAGE3;

char phone[16];
char datetime[24];

GPRS GSMTEST(PIN_TX,PIN_RX,BAUDRATE);//RX,TX,BAUDRATE

void loop() {
      // read the output on digital pins:
  int Level1 = digitalRead(5);
  int Level2 = digitalRead(6);
  int Level3 = digitalRead(7);

  // print out the value you read:s
  if (Level1 != 0){
    Serial.print("Level 1 =  "); Serial.print(Level1); Serial.print("   ");
    sendSMS();
  }
  else if (Level2 != 0){
    Serial.print("Level 2 =  "); Serial.print(Level2); Serial.print("   ");
    sendSMS();
  }
  else if (Level3 != 0){
    Serial.print("Level 3 =  "); Serial.print(Level3); Serial.println("   ");
    sendSMS();
  }
  delay(1);//delay ms

//void setup() {
//  loop();
//}

void sendSMS() {
  Serial.begin(9600);
  while(!GSMTEST.init()) {
      delay(1000);
      Serial.print("INIT ERROR\r\n");
  }
  Serial.println("GSM INIT SUCCESS");
  Serial.println("START TO SEND MESSAGE ...");
  Serial.print("..");
  delay(1000);
  Serial.println(".....");
  delay(1000);

  GSMTEST.sendSMS(PHONE_NUMBER,MESSAGE); //DEFINE PHONE NUMBER AND TEXT

}

void readSMS(){
     //READ THE INCOMING SMS MESSAGE
   Serial.println("   ");
   Serial.println("   ");
   messageIndex = GSMTEST.isSMSunread();
   if (messageIndex > 0) { //AT LEAST, THERE IS ONE UNREAD SMS
      GSMTEST.readSMS(messageIndex, message, MESSAGE_LENGTH, phone, datetime);
      //IN ORDER NOT TO FUL SIM Memory, IS BETTER TO DELETE IT
      GSMTEST.deleteSMS(messageIndex);
      Serial.print("FROM NUMBER: ");
      Serial.println(phone);
      Serial.print("DATE/TIME");
      Serial.println(datetime);
      Serial.print("RECEIVED MESSAGE: ");
      Serial.println(message);
   }
}


texts: request for a member "X" in something not a structure or a union

texts:
i was programming a Self Balancing    Robot, I am writing the code in vscode using platformio extension.

when i put the code i need to get the angle out of the gyro in another file (named angle.c) and including it in the main program, the ide throws with error, in every line I use the Wire library in the angle.c, however same code copy and paste it in the main program and it works.

P.S. the angle.c is just a file of functions and doesnot have any class.


texts: Error in program that measures distance from a ultrasonic sensor

texts:
I am trying to use an ultrasonic sensor in conjuncture with different devices like a proximity sensor and a solenoid and alarm.
This is how the project is supposed to work:
A container is placed on a fixture and the proximity sensor detects the placement of the container. Once the container is detected the ultrasonic sensor needs to be activated and the pulse time is measured and the distance is calculated. The container has unique features on each side and the aim of the ultrasonic sensor is to measure the distance and if the distance value is within the required spec then it should turn on a solenoid to allow the next operation or if it's outside the spec it should raise an alarm.
following is the code:
/*Objective of this project

1. To be able to detect when a container is placed in the wrong oreientation and cut of the supply to pneumatic system if so.
We will use the following devices to do so

1. Ultrasonic sensor to measure distance differences of both sides of the container
2. IR sensor to measure if the conatiner has been placed or not (This sensor will activate the ultra sonic sensor)
3. A soliend that will be controlled by the output of the ultrasonic sensor. The solenoid will control the air flow.

*/

int trigPin = 7;
int echoPin = 8;
int contSig = 2;
int solSig = 12;
int errSig = 13;
void setup() {

  Serial.begin(9600);
  pinMode(trigPin,OUTPUT);
  pinMode(contSig,INPUT_PULLUP);
  pinMode(echoPin,INPUT);
  pinMode(solSig,OUTPUT);
  pinMode(errSig,OUTPUT);

  }

void loop() {
  if (digitalRead(contSig) == 0){
    Serial.println(digitalRead(contSig));
    digitalWrite(trigPin,LOW);
    delayMicroseconds(10);
    digitalWrite(trigPin,HIGH);
    delayMicroseconds(10);
    int duration = pulseIn(echoPin,HIGH);
    Serial.println(duration);
    float dist = (duration/2) * 0.034;
    Serial.println(dist);
    if (dist >=20 && dist <= 60){
      digitalWrite(solSig,HIGH);
      digitalWrite(errSig,LOW);
    }
    else{
      digitalWrite(solSig,LOW);
      digitalWrite(errSig,HIGH);
    }
  }

}

I am facing a few issues.
1.The first If statement at the beginning does not seem to work properly.
2.The output on the serial monitor alternates between zeros and actual values.  I am not sure why this set of zeroes keeps coming inbetween but this will make the project fail.
Following is the output from the serial monitor:
0
0
0.00
0
2892
49.16


texts: Az Delivery ESP32 DevKitC V2 PIN names/number

texts:
i wonder where to find out the PIN names for the Az Delivery ESP32 DevKitC V2.
There is a pin out graphic, but it does not say how the Pin addresses are:
https://cdn.shopify.com/s/files/1/1509/1638/files/ESP_-_32_NodeMCU_Developmentboard_Pinout_Diagram.jpg?4479111012146266271
I thought maybe it's just the number of the GPIOs but that's wrong. In the first example script only PIN 1 was named as the address for the board intern LED.


texts: One ISR should be called, but both ISR has been called on Arduino UNO

texts:
I experimenting with the interrupt ISR using Arduino Uno. In my circuit, I am taking two mechanical switches that are connected with Uno's interrupt pins, pins 2 and 3, and also taking a built-in LED to confirm the ISR call.

My logic is when I press switch1 (which is connected to pin 3) or I press switch2 (which is connected to pin 2) LEDs should be turned on/off by the interrupt service routine.

My problem is that when I pressed switch1 and both ISR are called multiple times.

Here's my code:

const int mechanicalSwitchUpPin = 2, mechanicalSwitchDownPin = 3;

volatile byte stateSwitchUp = HIGH, stateSwitchDown = HIGH;

inline void upCallback()
{

  Serial.println("u");

  stateSwitchUp = digitalRead(mechanicalSwitchUpPin);

}

inline void downCallback()
{

  Serial.println("d");

  stateSwitchDown = digitalRead(mechanicalSwitchDownPin);

}

void setup()
{

  Serial.begin(115200);

  pinMode(13, OUTPUT);

  pinMode(mechanicalSwitchUpPin, INPUT);

  pinMode(mechanicalSwitchDownPin, INPUT);

  digitalWrite(mechanicalSwitchUpPin, HIGH); //Enable Pull-Up resistor to this pin

  digitalWrite(mechanicalSwitchDownPin, HIGH);//Enable Pull-Up resistor to this pin

  attachInterrupt(digitalPinToInterrupt(mechanicalSwitchUpPin), upCallback, RISING);

  attachInterrupt(digitalPinToInterrupt(mechanicalSwitchDownPin), downCallback, RISING);

}

void loop()
{

  !stateSwitchUp ? digitalWrite(13, HIGH) : digitalWrite(13, LOW);

  !stateSwitchDown ? digitalWrite(13, HIGH) : digitalWrite(13, LOW);

  delay(1);

}

Here is the output during one short press/release of the button connected to pin 2:

17:10:06.231 -> d

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> d

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> d

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> u

17:10:06.231 -> d

17:10:06.231 -> u

17:10:06.264 -> u

simulate this circuit – Schematic created using CircuitLab


texts:
After countless attemps on making this thing work i'm not sure what the hell is going on. First of all you can't use the normal IR library because Attiny85 is crap and due to timer isses it wont work. So basicaly you need just the specific part which gets the data from the remote and thats all.
This is what i did but i failed badly again.
This time i used the simplest possible code which works perfectly on the Arduino UNO but it wont do anything on the Attiny85
The code
int irPin     = 4;
int tipPin    = 3;
int start_bit = 2200;    //Start bit threshold (Microseconds)
int bin_1     = 1000;    //Binary 1 threshold (Microseconds)
int bin_0     = 400;     //Binary 0 threshold (Microseconds)

boolean state = 0x0;

void setup() {
   pinMode(tipPin, OUTPUT);
   pinMode(irPin, INPUT);
   //Serial.begin(9600);
   //Serial.println("IR/Serial Initialized: ");
}

void loop() {
   int key = getIRKey();   //Fetch the key
   //Serial.println(key);
   if (key != 0) {
     state != state;
     digitalWrite(tipPin, state);
   }
   delay(400);    // avoid double key logging (adjustable)
}

int getIRKey() {
  int data[12];
  int i;

while(pulseIn(irPin, LOW) < start_bit); //Wait for a start bit

for(i = 0 ; i < 11 ; i++)
  data[i] = pulseIn(irPin, LOW);      //Start measuring bits, I only want   low pulses

  for(i = 0 ; i < 11 ; i++)             //Parse them
  {
    if(data[i] > bin_1)                 //is it a 1?
data[i] = 1;
else if(data[i] > bin_0)            //is it a 0?
data[i] = 0;
else
return -1;                        //Flag the data as invalid; I don't know what it is! Return -1 on invalid data
  }

  int result = 0;
  for(i = 0 ; i < 11 ; i++)             //Convert data bits to integer
    if(data[i] == 1) result |= (1<<i);

  return result;                        //Return key number
}

The ouput values are 3-digit numbers which work OK and i'm not even checking the value here. Just if something came in. And it doesn't bloody work!!!!
Stuff i've already checked

The circuit
If the pin works
If the timers are set correctly
Using adafruits library
Changing every possible core
If the receiver works
The wiring


texts: /dev/cu port resource always busy on OS X 10.10

texts:
Is there any reason why is my /dev/cu port always busy? How can I fix that?

It happened on both Uno clone and Spark Core.

The problem is, I'm having issues doing serial communication. Where (as a programmer) I'm seeing something like dropped packets with /dev/tty port. I did a quick test running it on Win 7 (a loaner PC), it works fine...

The code for now is extremely simple. It waits for a command, and write a response.

String str = String(30);

void setup()
{
    Serial.begin(9600);
    str = "";
}

void loop()
{
    if (Serial.available() > 0) {
        char inChar = Serial.read();
        if ((inChar == '\n') || (inChar == '\r') || (inChar == 'z')) {
            str.trim();
            if(str == "READ") {
                String x = String(random(27, 45)) + "," + String(random(45, 300)) + "," + String(random(35, 250));
                Serial.println(x);
            }
            str = "";
        }
        else {
            if (str.length() < 30) {
                str += inChar;
            }
            else {
                str = "";
                str += inChar;
            }
        }
    }
}


texts: No Data Received on Serial Port & Unable to DFU Reset. Advice?

texts:
Having a problem running my original code that I tested last week, which worked on multiple days last week.

I tried to do a DFU reset and update the BootLoader, but it didn't work. I checked the baudrate and board selections in the Tools tab, but those were fine.

I didn't change anything in the code, I checked the wires on the hardware setup (nothing looks loose).

Thought it could be an error with the USB cable, changed the USB cable to a different one, still same error.

Also - using a Mac. But the same issue arose on the Windows PC. Did not try to reset using the Windows computer, but reset issue has more to do with the other hardware?

Checked the serial port - and it's selected to right one.


texts: Frequency Doesn't increase when Button Is Pressed

texts:
I’m trying to output a frequency that can be increased and decreased by using 2 buttons.  I’m trying to first of all configure the first button (which increases the frequency). I’m trying to also add button denouncing to not get incorrect button states. I’ve commented out anything that relates to button 2.

#include <TimerOne.h>
//Button States
boolean buttonState = LOW;
//boolean buttonState2 = LOW;

 boolean oldbutton1state = LOW;
//boolean oldbutton2state = LOW;

boolean newbutton1state = LOW;
//boolean newbutton2state = LOW;

//Time period in ms (T)
int period = 1000;
//int period2 = 1000;
float period_float = 1000.0;

//Output pins
int sig_out = 9;
//int sig_out2 = 10;

//Input Pins
int button =2;
//int button2 =3;

void setup()
{
  Serial.begin(9600);
  pinMode(button,INPUT_PULLUP);
  //pinMode(button2,INPUT_PULLUP);
  pinMode(sig_out, OUTPUT);
  //pinMode(sig_out2, OUTPUT);
  Timer1.initialize(1000);
  Timer1.pwm(sig_out,512,period);
  //Timer1.pwm(sig_out2,512,period2);
 }

void loop()
{
   buttonState = digitalRead(button);
   //buttonState2 = digitalRead(button2);
   newbutton1state = debounceButton(buttonState);

    if ((newbutton1state != oldbutton1state) && (newbutton1state == HIGH))
 {
       oldbutton1state = newbutton1state;

     float freq_change = 100.0/1000000.0;
  Serial.println(freq_change);

  period_float = (period_float)/(1+(period_float*freq_change));
  Timer1.setPeriod(period_float);
  Serial.println(period_float);

  Timer1.pwm(9, 512);
  buttonState=LOW;
  Serial.print("Signal 1 Frequency: ");
  float freq = 1000000.0/(period_float);
  Serial.print(freq);
  Serial.println("Hz");

  delay(100);
   }
}

boolean debounceButton(boolean state)
{
  boolean stateNow = digitalRead(button);
  if(state!=stateNow)
  {
    delay(50);
    stateNow = digitalRead(button);
  }
  return stateNow;
}

The issue is, when I load the code onto the Arduino, a 1KHz signal is being outputted, but every time I press button, nothing happens. I just wanted to know if anyone could shed light onto this issue. I think it may be due to the debouncing function (that it doesn’t work properly).


texts: Multiple upload/ Synchronization problem

texts:
I am trying to do an experiment with Arduino Uno r3 board plus a 2-channel relay shield. What I need to do is to alternatively turn on and off the relay shields. So, it requires multiple compile and upload of the program to assign values to corresponding pins. What I have seen by now is that uploading the program to Arduino is a kind of painful process and it requires nothing to be connected to pins 0 and 1 to prevent synchronization errors. So, I was wondering how I can do my experiment without having to mount/unmount relay shield each time I want to upload a new program into it.

Thanks in advance


texts:
I'm using a 12v fan and 12v LED modules in my project, so I need about 400mA by their combined specs. I have a 12.6v dc regulated power source that can give ~700mA I wish to use, and since it has a rather small form factor I would also like to power my Arduino Diecimila with it. I'm using PWM from pins 10 and 6 to go through N-channel MOSFETs in order to control both the LEDs and the fan. Anyway, in the Arduino Diecimila board page it says the recommended voltages are between 7-12v, and beyond that it can handle 6-20v, but it might cause the voltage regulator to heat too much, which might damage the board. So, my question is that: will 12.6v really damage my board, or is it within some margin of error? The actual voltage I got when I checked my power supply was 12.55V. Can I maybe just dial it down a bit somehow?

Thanks in advance,

UriSh.


texts: ESP32 AsyncWebServer SPIFFS problem loading page

texts:
I can load spiff docs, but I get a 404.  Wireless works, IP addressing works and I can load other examples successfully.  This simple image load ino is giving me fits!
#include <WiFi.h>
#include <AsyncTCP.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
const char *ssid = "x";
const char *password =  "123456789";
IPAddress staticIP(10,0,0,1); //ESP static ip
IPAddress gateway(0,0,0,0);   //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255, 255, 255, 0);  //Subnet mask

AsyncWebServer server(80);

void setup() {
  Serial.begin(115200);
  WiFi.softAP(ssid, password);

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{request->send(SPIFFS, "/index.htm", "text/html");});

server.on("/image.png", HTTP_GET, [](AsyncWebServerRequest *request)
{request->send(SPIFFS, "/image.png", "image/png");});

server.begin();

}//END setup

void loop()
{
}

<!DOCTYPE HTML>
<html>
<head>
     <meta charset='UTF-8'>
</head>
<body>
     <img src="image.png" alt=" image goes here">
</body>
</html>


texts: Is my Arduino destroyed or are the pins destroyed?

texts:
I made a working model of Bluetooth light control with arduino and Bluetooth. Everything worked fine and then after some time I connected the circuit again it didn't work and the pins 7,10,11,12 aren't working . I was using a Bluetooth shield but I tried the simple LED flash program and even that's not working .

Please suggest any good way of making it working again or at least explain what happened with it.


texts: Using two sensors with delay concurrently

texts:
I want to use an ultra-sonic sensor and the led concurrently. I want the led to blink every 0.2 seconds and the ultra-sonic to measure distance without regard to the blinking.

The problem is I have the following code for blinking:

digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(200);

which makes the ultra-sonic sensor to be delayed as well, but I want it to keep measuring distance.
Any tips?


texts: Where is the definition of system_adc_read() in the esp8266 Arduino code?

texts:
Where is the definition of uint16 system_adc_read(void) in the esp8266 Arduino code?

I can see it being declared in Arduino/tools/sdk/include/user_interface.h, however there seems to be no definition of this. system_adc_read() gets called in analogRead() in Arduino/cores/esp8266/core_esp8266_wiring_analog.c

I suspect system_adc_read() calls system_adc_read_fast() to read the ADC, but can't actually find it in the code! Could somebody please point me to this? I've been struggling for quite some time.

Purpose: To manipulate the system_adc_read() in ESP8266 to get higher ADC sampling rates. Right now ADC sampling rate is 10ksps. I want it to be more than 30-40ksps.


texts:
This is code about a keypad lock. The user can unlock the device by entering the secret code. To lock it again they press "#" or "*".

I want to let the green LED turn on for about 0.5 seconds then return to the first line of the loop: char key = keypad.getKey();.

The problem is that this code makes the green LED turn on forever after we enter the correct secret code or until we enter "#" or "*".

void loop() {
  char key = keypad.getKey();
  if (key=='*'||key=='#') {
    position = 0;
    setLocked(true);
  }
  if (key==secretCode[position]) {
    position ++;
  }
  if (position ==3) {
    setLocked(false);
  }
  delay(100);
}

void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
  }
}


texts: How do I change the default LED pin for displaying uploading

texts:
I made a board for my project based on Arduino Pro Mini. The problem is, that I had to put the LED on pin 4 instead of pin 13.

What setting do I have to change to make pin 4 the default one? Or do I have to write my own Board Library?


texts: What are these stray resistors on the Arduino Mega schematic?

texts:
I am using the Arduino Mega schematic found here and it's mostly clear, but there are a few resistors floating in the middle and I'm not quite sure what they're for or where they go:

Does anyone know what these are and where they go?


texts: Error taking address of temporary array when passing compound literal array

texts:
I have an Arduino sketch that passes an array into a method as a compound literal, but for some reason I keep getting the following error:

void setup() { }
void printConcatLine(char chunks[][20]) { }

void loop() {
  printConcatLine((char[][20]){ "{", "255", "}" });
}

I've also tried passing the number of the pointers/length of the array, and explicitly terminating it:

void setup() { }
void printConcatLine(char *chunks[]) { }

void loop() {
  printConcatLine((char*[]){ "{", "255", "}", NULL });
}

...and

void setup() { }
void printConcatLine(char chunks[][20]) { }

void loop() {
  printConcatLine((char[][20]){ "{", "255", "}", "" });
}

But they both produce the same error.

What is the correct method of passing the compound literal array as a method parameter?


texts:
I'm working on TinkerCAD, I want to design and simulate a circuit in which there are following components. 1. 1 RGB LED 2. 1 Push button 3. 3 Photo-resistors. 4. 1 Arduino board. So the light should be off at the starting. When the push button is pressed for the first ever time, the LED should light up as red, and then the brightness of the red color should be able to controlled by one of the three photo-resistors used, the second time when the push-button is pressed the LED should light up as green and green color this time should be controlled by another photo-resistor..when the button is pressed for the third time , the LED should now change to blue color and the third photo-resistor should be able to control the brightness of the blue color. And this cycle should go on, upon pressing the Push button.

please tell me what's wrong.

Code looks like this

int button_state = 0;//declaring a variable
int counter;//declaring another variable,will keep count of which color to be lighted
const int pRed = A2; //assigning pin A2 as pRed
const int pBlue = A1; //.............A1....pBlue
const int pGreen = A0; //............A0.....pGreen
int inputRed;//adjusted value of led brightness will be stored
int inputGreen;
int inputBlue;
const int ledRed = 9;
const int ledGreen = 11;
const int ledBlue = 10;

void setup()
{
  pinMode(2,INPUT);
  pinMode(ledRed,OUTPUT);
  pinMode(ledGreen,OUTPUT);
  pinMode(ledBlue,OUTPUT);
  pinMode(pRed,INPUT);
  pinMode(pGreen,INPUT);
  pinMode(pBlue,INPUT);
}

void loop()
{
  button_state = digitalRead(2);// reading the button state
  inputRed = analogRead(pRed);// Reading the value from A2 pin
  inputRed = map(inputRed,0,1023,0,255);//value from A2 pin adjusted for led's brightness
  if (button_state == HIGH) {
    counter = 0; // Declaring counter as 0 again
    analogWrite(ledRed,inputRed);
    analogWrite(ledGreen, 0);
    analogWrite(ledBlue, 0);
    delay(10);// Wait for 10 millisecond(s)
    green();// Jumping to green
  }
}
void green()
{
  while (counter == 0){//counter was declared 0 in loop function,so the code won't go ahead till it's 0 only
  button_state = digitalRead(2);//for reading the button state once again
  inputGreen = analogRead(pGreen);//reading the signal from A0 as it is the inputpin for photoresistor for green light
  inputGreen = map(inputGreen,0,1023,0,255);  //value from A0 pin mapped
  if (button_state == HIGH) {
    counter++; // Increasing counter by 1 so that it becomes 1 now.
    analogWrite(ledRed,0);
    analogWrite(ledGreen,inputGreen);
    analogWrite(ledBlue,0);
    delay(10);//wait for 10 millisecond(s)
    blue(); //jumping to function for blue led now
  }
}
}
void blue()
{
  while (counter == 1)//using while, so that the code won't go ahead if counter=1,as made in function for green light
  {
  button_state = digitalRead(2);
  inputBlue = analogRead(pBlue);//reading value from A1 pin
  inputBlue = map(inputBlue,0,1023,0,255);//value from A1 pin mapped
  if (button_state == HIGH) {//
    counter++;
    analogWrite(ledRed,0);
    analogWrite(ledGreen,0);
    analogWrite(ledBlue,inputBlue);
    delay(10);//wait for 10 millisecond(s)
  }
  }
}


texts: Broadcast data to radius of at least 500 meters

texts: I need to broadcast small amounts of data in a radius of about 500 meters to 2 Kms. in real time. Any compatible receiver in the range should be able to receive that data. Is there a suitable module for the same? I am considering HC-12 but don't think it can used for broadcasting data to all the surrounding receivers.


texts:
I'm starting fiddling with a Due but I can't seem to be able to communicate over USB with it. Here is my code:

int bauds = 9600;

void setup() {
    SerialUSB.begin(bauds);
}

void loop() {
    if (SerialUSB.available())
        serialUSBEvent();
}

void serialUSBEvent() {
    String str = SerialUSB.readString();
    SerialUSB.write(str.c_str());
}

As you can see, I try with the bare minimum but my output consoles (2 COM port for the 2 usb connections, just in case I messed up which is which) stay blanks, whatever I send them...


texts: How to write makefile-compatible sketches?

texts:
I'd like to write my sketches so that I can either build/upload them using the Arduino IDE, or optionally using GCC and a makefile.

I know about including the function declarations at the top, but is there anything else to do in order for my sketch to be considered valid C++ by my compiler?

Update 1

Understanding what the Arduino IDE does to .ino and .pde files is fine, but extraneous to my question, so this is not a duplicate. What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE and g++.

The official(?) makefile available here explains what to do if using the makefile instead of the IDE:

# The Arduino environment does preliminary processing on a sketch before
# compiling it.  If you're using this makefile instead, you'll need to do
# a few things differently:
#
#   - Give your program's file a .cpp extension (e.g. foo.cpp).
#
#   - Put this line at top of your code: #include <WProgram.h>
#
#   - Write prototypes for all your functions (or define them before you
#     call them).  A prototype declares the types of parameters a
#     function will take and what type of value it will return.  This
#     means that you can have a call to a function before the definition
#     of the function.  A function prototype looks like the first line of
#     the function, with a semi-colon at the end.  For example:
#     int digitalRead(int pin);

...but this doesn't explain how use both the IDE and a makefile.

Update 2

I recently found PlatformIO which doesn't answer this question directly, but does automate a lot of the process (generates Scons files for you) and so far I prefer the workflow over both the Arduino IDE and the source+makefile approach.  Good support from the authors as well.


texts: Is it possible to access GPIO9 and GPIO10 as DIO?

texts:
I have a nodemcu dev board with the esp12 chip. (Not the esp12e one).
I have tried to make use of gpios 9 & 10 for digital output. On the board, they are marked as SD2 & SD3. I suppose they must be serial data pins by default.
Ideally you can change the pin functions using the PIN_FUNC_SELECT() macro. So I tried the following:
PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_DATA3_U, FUNC_GPIO10);

However, on flashing this code, I notice my MCUs reboots. So it must have crashed at some point.
Am I doing this right?
PS: I was hoping to have at least 12 pins that can serve as digital output.


texts: I want to use a wifi shield, as well as a 2.8 inch touch LCD shield; both would fit the arduino uno V3 nicely.  Is that the best microcontroller to use


texts: DS18B20 setting resolution without addressing

texts:
As i understand the dallas library, there are two ways of referencing the sensor, one is to refer to the address, and the other is just to grab it as it is indexed.(gettempbyindex)

I want to know how to set the resolution of the sensor when i'm using the gettempbyindex method, all the examples i can find seem to only set resolution when specifying the address explicitly..

Is it even possible?


texts: Why can the Xbox360 not detect the Arduino Leonardo as keyboard?

texts:
Arduino Leonardo as keyboard in the computer works! But not with the Xbox360.
The Teensy works perfectly on the PC but how to emulate a keyboard device for the Xbox360.

I know the Xbox360 has security IC, but a simple USB keyboard works!

What is the diference ?

How i can emulate an usb keyboard for the Xbox360?


texts: Sharp GP2Y0A710K0F IR sensor behaving strangely

texts:
I have just purchased a new Sharp GP2Y0A710K0F IR sensor online. As a sanity check, I wrote this simple code to check if the sensor is working correctly. The code is expected to print output voltage from the sensor, which is based on the distance

int sensorpin = A5;
int val = 0;

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

void loop()
{
val = analogRead(sensorpin);
Serial.println(val);
delay(100);
}

Now the output is quite strange. The output values start from zero and keep on increasing until they reach 1023, and then gradually decrease down to zero and this keeps on happening, even if something is kept in front of the sensor.

Is my sensor a faulty one? or is it supposed to give out similar outputs. If it has to, how do I convert these values to meter or centimeters.

The product description on the manufacturer's website said that it has a 3 pin interface, however it has a 5 pin one, the wires being Red, Black, Yellow, White, Green if seen from the left side. I guessed from the datasheet that Red and Black are for power and Yellow for signal output and hence I have connected only these 3 wires. The Green and White wires are unconnected. Also, pin numbers aren't marked.


texts: Undefined reference to stdlib (strtof) while compiling

texts:
I'm trying to run the AzureIoTProtocol_MQTT/esp8266 example, but I get linker errors:

  Archiving built core (caching) in:
  /var/folders/fj/y3vtrz597kv4885q1b_5qypr0000gn/T/arduino_cache_934614/core/core_esp8266_esp8266_d1_mini_CpuFrequency_80,UploadSpeed_921600,FlashSize_4M3M_e1e103f2055a19e071ac9522162e1787.a
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function sscanfd':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
  undefined reference tostrtoull'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
  sscanfllu':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
  undefined reference tostrtoull'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o:(.text.CreateAgentDataType_From_String+0xac):
  undefined reference to strtof'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
  CreateAgentDataType_From_String':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:3571:
  undefined reference to `strtof' collect2: error: ld returned 1 exit
  status

The issue can be broken down to the call to strtof function call. I get the same error with only this very simple code snippet:

#include <stdlib.h>

void setup() {
  char szOrbits[] = "686.97";
  float f;
  f = strtof (szOrbits, NULL);
}

void loop() {
}

Tested environment: Mac OS X 10.13.2 with Arduino 1.8.3 AND Windows 10 with Arduino 1.8.5.


texts: How to use arduino IDE to compile .s files

texts:
Hi I'm new to arduino and im using it to learn assembly for my computer hardware 101 class, I read online that I can make the IDE accept .s files and compile them to the board but I dont know how to do this (something about editing the source code and recompiling the IDE?).

Could I get a step by step walk through? Assuming it's relatively simple, or just a link to some relevant documentation that's not a literal reference manual :-).

EDIT
As terrible as it is,I'm working from a macbook pro


texts:
My sensor outputs an int. I would like this to be an array of strings so I can send it with my 433MHz transmitter.

Converting an int to a string to an array of strings seems to be extremely complicated. I've tried multiple approaches.

The error is always:

  array must be initialized with a brace-enclosed initializer

#include <VirtualWire.h>

const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;
int mostureSensor = 0;

void setup()
{
  // Initialise the IO and ISR
  vw_set_tx_pin(transmit_pin);
  vw_set_rx_pin(receive_pin);
  vw_set_ptt_pin(transmit_en_pin);
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(1000);   // Bits per sec
}

byte count = 1;

void loop()
{
  // read the input on analog pin 0:
  String sensorValue = String(analogRead(mostureSensor));

  char charBuf[7];
  char msg[7] = sensorValue.toCharArray(charBuf, 7);

  //char msg[7] = {'h','a','l','l','o',' ','#'};
  Serial.println("sending");
  msg[6] = count;
  digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  digitalWrite(led_pin, LOW);
  delay(1000);
  count = count + 1;
}


texts: Recovering from lost USB connection (Leonardo to Raspberry Pi)

texts:
I have several Arduino Leonardos connected to a Raspberry Pi (running Ubuntu) via USB. They appear as /dev/ttyACM0, /dev/ttyACM1, etc.

Occasionally, one will disappear and even pressing the Arduino's reset button won't bring it back. Is there any way to "refresh" or "reinitialize" the ttyACM* devices to make them reappear without having to reboot the Raspberry Pi?


texts: Having difficulty uploading sketch to an Arduino Pro Mini

texts:
Having developed and tested a project using an Arduino Uno, I would now like to upload it to an Arduino Pro Mini (5V, 328, 16MHz) for semi-permanent, long-term use, but I can't get any sign of life from the Pro Mini.

I'm using the latest Arduino IDE (v1.6.0 with Java 6, on Mac OS X Mavericks), and I've got a USB 2.0 to TTL UART 6PIN CP2102 Module Serial Converter to connect the Pro Mini to the Mac, and I've selected Tools —> Board —> Arduino Pro or Pro Mini (5V, 16MHz) w/ ATmega328.

The problem is that I don't see a suitable serial port in the list. When I plug in the Arduino Uno, "/dev/tty.usbmodem1421" immediately pops up in the Tools —> Serial Port menu, but I don't see anything similar with the Mini Pro.

The problem is probably in the connection between the USB/TTL converter and the Mini Pro, so my question is: which pins should connect to which?

FWIW the USB/TTL converter was supplied with a 5-core (not 6-core) cable to connect its 6 pins.

So do I connect Tx—>Tx and Rx->Rx, or should they be crossed over? It's fairly clear that "5V" connects to "Vcc" and "GND" goes to "GND", but what about CTS and DTR?

Also FWIW, I have googled this, and I have read a number of other posts and answers on StackExchange, but the fact that I'm here writing my question means that I'm still stuck. Any and all constructive suggestions will be appreciated. Thanks!


texts: using an ESP8266 shield on my Arduino Uno R3 with an unofficial library

texts:
I'm using the following Makefile: https://github.com/sudar/Arduino-Makefile
It works very well and I was able to get my LED to blink.

Now I bought a WiFi Shield which is NOT supported officially by the Arduino WiFi library.
It is the following one I bought: ESP8266 ESP-12E CC3000 UART WIFI Wireless Shield Board Modul für Arduino UNO R3 - you can find this on ebay: http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

What I now am about to do is to include the open source library for the ESP8266 which you can find here: https://github.com/esp8266/Arduino#documentation

Now when I try to upload my sketch it tells me that certain dependencies are not resolved. Like this one here #include <functional> which I was not able to include manually. My main problem here is that the github page of the ESP8266 library isn't providing enough information for me how I can get the working lib to use in my sketch.
I need to know how I can get this library to work in my sketch!


texts:
i use the example sketch of SD card presented in Arduino IDE.
It runs well, but when i reboot my Adruino Mega by the reset button, the SD card initialization fails.
To fix it, i need to remove the SD card, insert it in his socket and reboot the board again. Then, SD card initialization is OK.
How can i update my code to try initialize the SD card until initialization is OK?
Also, can you explain me where come this bug ?

See the example SD card setup on the Arduino Mega:

Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");


texts: Project Idea Guidance: LED strips that react to music

texts:
I want to build something similar to the ViVi as shown in this video: ViVi - Fully Automated Reactive Music LED Controller with VibeSync Technology. Compact and Wearable, but I would like to make something similar myself utilizing Arduino. I would probably be using 2-3 WS2812 LED strips and would like to interface it using an Android/iOS app via Bluetooth since the Wi-Fi network at my University only allows certain devices to be registered, Arduino (with a Wi-Fi shield) is unsurprisingly not one of the accepted devices.

Programming the app's user interface is not an issue. I'm just new to interfacing Arduino BLE to applications and would like some guidance.  In the app UI I would have the music modes available, but I would also like to incorporate another view that would control the LEDs as normal, i.e on/off, color selection, fade, strobe, etc.

As far as the build goes, this is where I need a little more help. I would like to know how to go about this build in the most efficient way possible and what would be the best resources to use.

If anyone can point me in the right direction/provide some useful resources that would be awesome.


texts: Is it possible to load both the arduino bootloader and a sketch onto an atmega328p via icsp?

texts: i am familiar with uploading an arduino bootloader onto an atmega328p using another arduino via the arduino IDE. i have also installed software 'sketches' using that process which i believe leaves out the bootloader(meaning one wouldnt be able to upload new sketches in the future via usb). my question is: is it possible to load both the bootloader and a software program onto the chip via icsp? many thanks in advance.


texts: What are the fundemental differences of different Bluetooth modules for beginners?

texts:
I'm a beginner to microcontrollers and electronics, albeit not really to computers and programming.

Starting out with the Arduino, I came to a point whereby I'm really interested in getting my prototype to talk to a mobile device or a computer to send and receive data (for example, send sensor data or receive commands).

Looking out, I've found out that there are different bluetooth modules with varying pricing points. Further research into differences did not reveal much to me as being a beginner, I am struggling to understand what to look out for or how to choose.

My question here is:

What are the fundemental differences of different Bluetooth modules for beginners, such as:

HC-05
HC-06
HC-07

And what should one look for when buying a simple Bluetooth module for Arduino?