texts:
Im attempting a device that measures lean angle. I have an ESP8266 + MPU6050 + SSD1306 setup, and I've managed to build a shaky but somewhat functioning device.
What Id like to do is use the Adafruit_SSD1306 library to call the display.drawLine(x, y, x1, y1, color) function and have the line drawn to the measured angle output of the MPU6050.
The screen I'm using is 128 X 64
The MPU6050 is initially laying flat at 180 degrees, but is set and displayed as 0 degrees of tilt. The line is drawn vertically on the screen and pivots around x1 and y1 at 64, 64 respectively in the middle at the bottom of the screen.
If the MPU6050 pivots left like in the picture, the angle measurement itself is roughly correct, but the line indicator is showing more like 30 degrees than 45, and gets worse the larger the angle value.

My code:
#include <Adafruit_MPU6050.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>

const int MPU_addr=0x68;
int16_t axis_X,axis_Y,axis_Z;

Adafruit_MPU6050 mpu;
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);

int minVal=265;
int maxVal=402;

double x;
double y;
double z;
int tiltAngle;
double y2;

void setup(){
  Serial.begin(9600);
  Serial.println("MPU6050 OLED demo");

  if (!mpu.begin()) {
    Serial.println("Sensor init failed");
    while (1)
      yield();
  }
  Serial.println("Found a MPU-6050 sensor");

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

  display.display();
  delay(500); // Pause for 2 seconds
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setRotation(0);
}
void loop(){
  display.clearDisplay();
  display.setCursor(0, 0);

  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);
  axis_X=Wire.read()<<8|Wire.read();
  axis_Y=Wire.read()<<8|Wire.read();
  axis_Z=Wire.read()<<8|Wire.read();
    int xAng = map(axis_X,minVal,maxVal,-90,90);
    int yAng = map(axis_Y,minVal,maxVal,-90,90);
    int zAng = map(axis_Z,minVal,maxVal,-90,90);

     x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
     y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
     z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

     tiltAngle = (int) x - 180; // we want the tilt angle to be 0 degrees
     display.println(" ");
     display.println(" ");
     display.println(" ");

     // display only positive angle values for either direction of tilt
     if(tiltAngle > 0){ display.print(tiltAngle);}
     else if (tiltAngle < 0) { display.print(tiltAngle * -1);}
     else {display.print(tiltAngle);}

     display.drawLine(-tiltAngle + 64, 0,64,64,WHITE);
     display.display();
     delay(100);
}

Im aware that for my first y co-ordinate I will need to use some kind of formula to get the line to move down from 0 (the top of the screen) as the lean angle gets greater. I'm hoping someone could point me in the right direction for drawing the line at the angle given by the MPU6050.
I did consider using case statements for each angle value and drawing the line with fixed co-ordinates based on each angle value. But that seems too compute intensive and could take up too much of the DRAM. Is anyone aware of a simple formula I could use? Thanks for reading.


texts: What kind of control method in my code will allow me to control multiple servos with phase shifts

texts: I am building a quadruped robot, and I need to keep all four legs moving continuously and out of phase with respect to each other to produce a smooth gait and to prevent falling over. I wish to achieve this with 4 sets of 2 motors. Each set will move in the same way but not in sync. I have an Adafruit 16-Channel 12-bit PWM/Servo Driver - I2C interface - PCA9685 for this application. I have considered several implementations; delay () would be a poor choice because of the obvious delay between the current and next step in the gait cycle. I am also considering using ISR that will trigger when a certain time period passes, an estimated time to reach the desired position for example, but the interrupt method would not be much better than delay (). Another idea I have is to create a class that will receive the next position to move to for each leg and will continuously send the signal to the PWM driver. However, timing this would require some trial and error. Is there a conmon well-known method to send control signals with phase shifts?


texts: How to expand an Arduino when using a TFT display shield?

texts:
I am really new to this Arduino stuff. I can't figure out one of my problems on my own.

I am using this 2.4 TFT display shield on an Arduino Uno. It works fine so far: I have coded a little sketch for it that displays a start button and after tapping that it shows random colors.

Now I would like to connect a circuit with jumper cables that are used as sensors. When I touch one of the jumper cables the light connected will turn on.

The problem I have now is that this specific circuit is using an other Arduino because my first Arduino is already 'full' because the TFT shield is taking up all pins.

How can I resolve my problem? Is it possible to Stack Arduinos? Is it possible to connect those Arduinos somehow? Thanks in advance!


texts: Is there a compiler that I can use to run C on an arduino or any other way so that I can upload C programs to my arduino?


texts:
I have built a custom Arduino Micro PCB, but I have made a mistake, I accidentally attached an interrupt pin for a Gyro sensor to pin 12 of the Micro, not realizing it wasn't an external interrupt pin.

I tried using the interrupt pin change command found on the Arduino website, but I am having some trouble getting it working. If there is a way to make pin 12 on the Arduino Micro an Interrupt pin, how would I go about doing that in the simplest way.


texts: How to code multiple conditions inside if statement?

texts:
I have a system that checks the value of a moisture sensor and will also check the time

if (t.hour == 7 && t.min == 00 && moistureOneSensorValue >= 700) {
  RelayOne();
  RelayTwo();
}

When moistureOneSensorValue is greater than or equal to 700 it means the soil is DRY, so when all conditions inside the if statement are true the relayOne and relayTwo functions will be called.

My problem is that when moistureOneSensorValue is still moist the above if statement will result in false and the relayOne and relayTwo functions will not be called. I want Arduino to execute and call the relayOne and relayTwo functions and disregard the time. I use time so that the system will only call the relayOne and relayTwo functions in the morning at exactly 7 AM every day, but it needs to check/make sure that the soil is DRY...

Example

First thing in the morning the system will check the time and sensor value; if the if statement results in false the system will keep monitoring and try the if statement until the soil is DRY. But I think when that happens it will be over 7 AM.

Sorry for the messy explanation.


texts: How is IF( object ) evaluated? Follows from SD card example sketch

texts:
The "DumpFile.ino" example sketch from the SD library tries to open a file off an SD card, read its contents, and write them to the Serial Monitor. I am confused in how the following if() statement is evaluated:

File dataFile = SD.open("datalog.txt");

if (dataFile) {
// read and print, then close
}
else {
// print error message
}

There must be some implicit conversion on dataFile which depends on whether or not SD.open("myFile.txt") was successful. I would like to understand how this implicit conversion occurs. Which property of the File object determines if the if() statement evaulates true or false?


texts: How can you determine the duration of a timer interrupt?

texts: So I understand that when setting a timer interrupt you don't use nanoseconds or milliseconds, but the actual number of clock cycles. However, I don't understand how you would be able to setup a specific time this way. If I wanted my interrupt to go off every 20 milliseconds would I have to divide that by the duration of each clock cycle?


texts: Using Leonardo as keyboard: add wake and sleep functions

texts:
I want to use a Leonardo with USB chip to emit some commands via USB port to a digital piano computer (running Windows 7) for various functions. I've gotten the Leonardo to emit page up and page down functions using a simple project I found on the web. What I need now is the following set of functions: left arrow, right arrow, F11, wake, and sleep. What I need help with is:

where is the complete list of functions available with keyboard.press?
are wake and sleep among those available?
if they aren't, what header file could be modified to include them?

Thank you for any suggestions.


texts: Disabling i2c internal pull up resistors

texts:
How do you do this? I've been digging around and I can see that I should do this and supply my own external pull up resistors but I don't know exactly how to disable them. The pages I've been reading never explicity state how.

I'm trying to enable I2C between a leonardo and an uno, but I think the i2c bus is slowing down considerably because of the internal pullups. I want to switch to two 4.7k resistors but I can't figure out how to disable the internal ones. I know that the Wire library enables the internals by default, but how do I edit the library or disable the pullups in my sketch?

Maybe I just haven't been reading the right forums or articles, but if anyone could point me in the right direction that would be much appreciated.

EDIT: So the problem is probably with my setup or code, I'll put it down here. Everything I have before setup is importing libraries and variables like my mac, ip, placeholders for output, pwm, etc.

Master:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while(!Serial){
  }

  Wire.begin();

  Ethernet.begin(mac, ip);
  delay(1000);

  server.begin();
  if(server.available()){
    Serial.println("Client Available");
  }
}

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

  ethernetwrite();

}

void ethernetwrite() {
  EthernetClient client = server.available();
  while(client) {
    if(client.find("P")) {
      output = client.parseInt();
      pwm = client.parseInt();

      Serial.println("Begin Transmitting");
      Wire.beginTransmission(14);
      Wire.write(output);
      Wire.write('\t');
      Wire.write(pwm);
      Wire.endTransmission();
      Serial.println("Done Transmitting");

      Serial.print(output);
      Serial.print('\t');
      Serial.println(pwm);

    }
  }
}

Slave:

void setup() {
  Wire.begin(14);
  Wire.onReceive(wirewrite);

// *   - Base frequencies:
// *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
// *      o The base frequency for pins 5 and 6 is 62500 Hz.
// *   - Divisors:
// *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
// *        256, and 1024.
// *      o The divisors available p1on pins 3 and 11 are: 1, 8, 32, 64,
// *        128, 256, and 1024.

    // Leg 1
    pinMode(leg[1], OUTPUT); setPwmFrequency(leg[1],8); analogWrite(leg[1], offset);

    // Leg 2
    pinMode(leg[2], OUTPUT); setPwmFrequency(leg[2],8); analogWrite(leg[2], offset);

    // Leg 3
    pinMode(leg[3], OUTPUT); setPwmFrequency(leg[3],8); analogWrite(leg[3], offset);

    // Leg 4
    pinMode(leg[4], OUTPUT); setPwmFrequency(leg[4],8); analogWrite(leg[4], offset);

    // Mirror
    pinMode(leg[0], OUTPUT); setPwmFrequency(leg[0],clkdivisor); analogWrite(leg[0], 255);
}

void loop() {

    int time = 10;
    time = time*128/clkdivisor;

    // box(time, 255, 1); // box(delay time, radius pwm, pwm step size);
    // autodisplay();
    updateL();

}

void updateL(){
  if (output == 0) pwm = 255 - pwm;
  switch (output) {
    case 1: pin =  3; break;
    case 2: pin =  9; break;
    case 3: pin =  10; break;
    case 4: pin =  11; break;
    case 0: pin = 5; break;
  }
  //if (output < 5) {
    analogWrite(pin, pwm);
  //}
}

void wirewrite(int numBytes) {
  String message;
  while(Wire.available()>0) {
    char c = Wire.read();
    message.concat(c);
  }
  output = Wire.parseInt();
  pwm = Wire.parseInt();
}

When I send data to the master, on the serial monitor it freezes in the first wiring transmission or in the next few, and my slave doesn't seem to respond to the message being sent over i2c. My controls for my device and setup worked prior to my attempts with the Wire library, so there's no problem there.

EDIT: I also am sending a message that looks like this:
"P1 103"
every .4 seconds or so, but I usually can't get past the first transmission between the arduinos


texts:
Hello Arduino Stack Exchange,
I have an an enum instance called state:
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;
States state = SLEEP;

I would like to convert the value of state to a String so I can serially print it using Serial.println().
Currently, when I type String(state), I get a value 0, 1, etc.  I suppose this corresponds with the index of the enum's key.
How can I get it to return "SLEEP", "AWAKE", etc.?


texts: Dynamic allocation/ Pointer to Pointer to update an Array containing parameter

texts:
topicArray defined as follows:

const char* msgTopic = "Home/Messages";
const char* groupTopic = "Home/All";
char* deviceName = deviceTopic;
const char* topicArry[2] = {deviceTopic, groupTopic};

But deviceTopic can be changed during code run, and I wish that topicArray containg deviceTopic will have the correct value after deviceTopic has changed.

What is the right way doing so ?


texts: Will Arduino Mega support stepper motor NEMA 24, NEMA 34

texts: Will two stepper motor NEMA 24, 10 kg cm, 2. 8 amp, 24 vdc work at same time on Arduino Mega and when they stop stepper motor NEMA 34, 34 kg cm, 4amp, 24 VDC will work or not? This is my first project please help me to choose the controller.


texts: Measuring resistance conceptually and in code?

texts:
How would I measure resistance over a certain length? In this case the resistance is variable.

What I have in my head is that you would output a certain amount of current from one pin, and measure how much comes back from the other.

I'm not sure if this would work, or how to implement it in code.

I've seen this forum post, but it's not making much sense to me.

How can I measure resistance?


texts: Which external programmers work reliably with Arduino Mega?

texts:
When looking for alternate external programmers (ISPs), I am noticing that many are not Arduino Mega 2560 compatible (e.g. Pocket AVR Programmer, USBtinyISP).

I am looking for a reliable external programmer for the Arduino Mega that is compatible with the Arduino IDE. What are my options? Currently I have been struggling with the retired ArduinoISP programmer, which doesn't look like its going to work. Does anyone have proven experience with a given programmer and a Mega?

The suggested AVR-mkII doesn't seem to be available anymore either.


texts: How big of a difference is there between an Arduino Uno and the rest?

texts:
Lately I've been fooling around with a project for my Microsoft Sidewinder Force Feedback Pro Joystick. I've found out that there is a project currently for it built for the Teensy 2.0. On the page for the Teensy 2.0 there is a link for an Arduino Library for the very same project that was (I guess) converted. There isn't much documentation for it, and I don't think there is much progress being made on it anymore. However when I grab the files and try to upload it to my Arduino Uno it spits out an Unsupported device. Doing some digging around I found where it shows what devices are supported in the includes.h.. Which happen to be

#if defined(__AVR_AT90USB162__) || defined(__AVR_AT90USB82__)
 #define __AVR_AT90USBX2__
#elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
 #define __AVR_ATmegaXU4__
#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
 #define __AVR_AT90USBX6__
#else
 #error "Unsupported device"
#endif

Which ends up being the red arduino, arduino micro, arduino leonardo, and I think a few teensys.

What I want to know is if you can upload this code onto a UNO. I'm not really wanting to purchase a teensy just to check if this will work or not.


texts: I want to create 10 levels with one button but this code shows only level 1?

texts:
#include <Adafruit_NeoPixel.h>
const int PIN = 4;
const int NUMPIXELS = 10;
const int BUTTONPIN = 6;
int buttonState = 0;
int PINState = 0;
int level = 1;
int dt = 100;
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  pixels.begin();
  pinMode(BUTTONPIN, INPUT);
  Serial.begin(9600);
}

void loop(void) {
Serial.println(buttonState);
  buttonState = digitalRead(BUTTONPIN);
  if (digitalRead(BUTTONPIN) == HIGH) {
    if (buttonState == 0) {
      buttonState = 1;
    } else {
      buttonState = 0;
    }
  }

  if (buttonState == 1) {
    opdracht(level);
  }
  else {
    if (level >= 10) {
      level++;
    } else {
      level = 1;
    }
    pixels.clear();
  }
}

//level 1
//void opdracht1() {
//  pixels.setPixelColor(0, pixels.Color(150, 0, 0));
//  pixels.setPixelColor(5, pixels.Color(0, 0, 150));
//  pixels.show();
//}

void opdracht(int x) {
  if (x == 1) { //level 1
    pixels.setPixelColor(0, pixels.Color(150, 0, 0));
    pixels.setPixelColor(5, pixels.Color(0, 0, 150));
    pixels.show();
  }

  if (x == 2) { //level 2
pixels.setPixelColor(8, pixels.Color(150, 0, 0));
pixels.setPixelColor(6, pixels.Color(150, 0, 0));
pixels.setPixelColor(1, pixels.Color(0, 0, 150));
pixels.show();
  }


texts: What can cause an Arduino to "disconnect" from Windows?

texts:
I bought a DFrobot Beetle and it worked fine for probably an hour, then it just stopped working with Windows.

When I connect it to the computer I hear the "connect" sound, then within 5-7 seconds I hear the disconnect sound again.

I didn't do anything special with it. I connected a RDM6300 rfid reader and used an example code from a library.
I think the last thing I did was to change a string output message in the console.

From then on it just disconnects.
I tried to email DFrobot but didn't get a reply.

What could have caused this?
What can I do to make it work again?
The reset pin didn't work.
There is not enough time to replace the code on the board before it disconnects.


texts: Use input capture for multiple sensors simultaneously

texts:
I want to accurately time multiple digital input channels (readings from sensors) for the rising and falling edges. I need the precision of the Timer1 Input Capture. As far as I know the input capture only listens to pin D8 (for ATmega8). So, is there anyway to capture the inputs of multiple sensors?

Update:

I would like the reading to be as accurate as possible since I'm using the values to calculate motion tracking information. Concretely, I'm trying to build my own tracker for StreamVR's light house.


texts: DFPlayer Mini with its standard library does not being initialized

texts:
I have a DFPlayer Mini bought from AliExpress.
The player works correctly in standalone mode, but I am having troubles while using it with the following components:

Seeduino v4.0;
2GB Smartbuy MicroSD card.

When I try to use this standard sketch for Arduino to connect my Seeeduino V4 to the player:

if I set the serial like mySoftwareSerial(11, 10), the player's tiny LED turns on for 2 seconds, then it switches off, and after that, the board tells me the error message below (video here);
if I set the serial like mySoftwareSerial(10, 11), the player`s tiny LED switches on and remains being switched on, while the board tells me the error message below (video here):

DFRobot DFPlayer Mini Demo
Initializing DFPlayer ... (May take 3~5 seconds)
Unable to begin:
1.Please recheck the connection!
2.Please insert the SD card!

This module's image:

The circuit diagram:

simulate this circuit – Schematic created using CircuitLab
I have tried almost everything I could. I changed the filenames on my SD card, tried to use different pins, tried to use different wires..! I even tried to disconnect the speaker from the player!
I also had seen this message on the manufacturer`s forum:

I found that the solder joint on the TX pin was bridged to the SD card holder, effectively bridging the pin to the ground. Try a continuity test between the TX and ground. If they are connected you have a bad joint.
I was able to remove the excess solder and it worked fine after that. It's a medium difficulty soldering task.

Maybe, it`s my case?


texts:
I have an array of Strings in my code:

String BitSequence [257];

Each string will have 23~64 characters. At one point in my code, I have to use "myString.remove()" command and I don't want to apply any changes to my original strings. I need to make a copy and perform my commands on the copied string. I did:

MycopyString = BitSequence [1];

but it doesn't work. What tricks do I need to do here to make a copy?


texts:
I am trying to make a workaround for the delay function. I am trying to use the function in the Analog Write Mega example, by replacing delay with the function i made. However, whenever i use my function instead of delay i get incorrect led behaviour.

Here is the link to the example:

https://www.arduino.cc/en/Tutorial/AnalogWriteMega

Here is my code:

int currmillis = 0; //used in my function to find the current millis()
int prevmillis = 0; //used to hold previous value of currmillis
int boolval = 0;    //used to control whether to write the brightness value to the led or not
int time = 0;     //used in the delay function, difference between currmillis and prevmillis

int timeloop(int); //the function i wrote, it is at the bottom of the code

void setup() {
  Serial.begin(9600);
  for ( int i = 2; i <= 13; i++)
  {
        pinMode(i,OUTPUT);
  }
}//Setting the pins to output and allowing serial communication.

void loop (){

  for ( int thisPin = 2; thisPin <= 13; thisPin++ ) //to move from one led to the next
  {

    for ( int brightness = 0 ; brightness <= 255; brightness++) //change the brightness of the led
    {

      boolval = timeloop(2); //the delay function returns the time passed, if the time is greater than or equal to 2, the analogWrite will write the brightness to the led

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }// if 2 ms pass, the led brightness will increase from 0 to 255 and then decrease in the following loop from 255 to 0, Once it reaches 0, the main loop moves to the next led.

    }

    for ( int brightness = 255 ; brightness >= 0 ; brightness--)
    {
      boolval = timeloop(2);

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }
    }
          timeloop(100); // a delay of 100 ms using the function
  }
}

int timeloop (int interval){ // the delay function

  do{
    prevmillis = currmillis; //hold previous value
    currmillis = millis(); //find current value
    time = (currmillis-prevmillis);
  }while(time < interval);

  return time;
}

Thank you


texts: SendSMS example sketch hangs at PINMUNBER if statement

texts:
I'm using an Arduino shield connected to an Arduino Uno for sending text messages. I'm using one of the in built examples from the Arduino IDE for sending SMS by name - sendsms in the GSM examples. However, the code doesnt work at all... it keeps hanging at the line

if (gsmAccess.begin(PINNUMBER) == GSM_READY)

and never goes beyond it.

I didn't keep any pincode for my SIM card. please help


texts:
I got a question about externally powering my NodeMCU V3. It has an onboard voltage regulator (3v3) which breaks out to 3 header pins. Now I want to power 3v3 from an external board. Can I supply 3v3 to all of those pins at the same time? (Basically connected in parallel).
Anyone has done this before or has this experience with NodeMCU V3?

I have supplied a link below:
https://www.theengineeringprojects.com/2018/10/introduction-to-nodemcu-v3.html

Thanks a lot!


texts: I²C between ATTiny85 (8MHz) and Arduino Uno

texts:
I keep receiving the following error in myATTiny85-Slave code below:

sketch_mar12a.ino: In function 'void setup()':
sketch_mar12a:19: error: 'class USI_TWI_S' has no member named 'onRequest'

I have downloaded TinyWireS and TinyWireS.h clearly has a public function onRequest. I opened the .ZIP file (downloaded from https://github.com/rambo/TinyWire) and drag-dropped TinyWireS folder into the Arduino libraries folder. This is how I install ALL libraries.
I am using Arduino 1.0.6
What am I doing wrong?
ATTiny85-Slave Code:
#include "TinyWireS.h"                  // wrapper class for I2C slave routines
#define I2C_SLAVE_ADDR  0x26            // i2c slave address (38)

byte t=10;

void setup()
{
   TinyWireS.begin(I2C_SLAVE_ADDR);      // init I2C Slave mode
   TinyWireS.onRequest(requestEvent);
}

void loop()
{
}

void requestEvent()
{
   TinyWireS.send(t);
}

Arduino Uno-Master Code:
 #include <Wire.h>
 #define I2C_SLAVE_ADDR  0x26            // i2c slave address (38)

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

 void loop()
 {
      byte num;

     // read 1 byte, from address 0x26
     Wire.requestFrom(I2C_SLAVE_ADDR, 1);

     while(Wire.available()) {
          num = Wire.read();
     }

     Serial.print("num = ");
     Serial.println(num,DEC);
 }


texts:
I am working on a robot which uses Ackermann's steering principle. Now the steering principal itself is in the development stage and the first prototype is pretty much good except for the fact that it can get turned very easily.

So I was hoping to find a way to lock the servo operating the steering mechanism so that it only rotates when the servo does. Any way to do that??

I'm using a UNO.

Thanks!


texts: How do I change number and bracket colors in the arduino IDE?

texts:
I recently personalized my arduino IDE (changed the background color, input text color, etc....) by going into the theme.txt file and replacing some hexadecimal values. I made the background black and the text lime green, but for some reason numbers and brackets still remain black, thus I can't see them against a black background. Anyone know how to fix this? I would really appreciate the help, got sick of looking at a white background when making sketches.

Sal


texts: Reducing the noise of an SSD1306 display by reducing pre-charge in Adafruit SSD1306 library

texts:
I have issues with electrical noise on my board (>300mV switching noise on top of 3.3V rail, its quite a lot), which is generated by my I2C SSD1306 OLED display. After some research I found that the noise may be reduced by changing the pre-charge duration in the SSD1306 controller. I am using an Arduino IDE with Adafruit_SSD1306.h library to program my chip. As I understand the initialization bits should be passed via I2C to the controller.
I found the following command in the Adafrui_SSD1306.cpp:

And the relevant bit of datasheet:

The D9 register is defined as SSD1306_SETPRECHARGE in Adafruit_SSD1306.h:

I am using the following code:

void setup(){
...
display.ssd1306_command(SSD1306_SETPRECHARGE); //0xD9
display.ssd1306_command(0x11);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
}
...

I am trying to set to 0x11, so to give the pre-charge byte lowest value possible. I've also tried putting the same command into the loop. Nothing has any effect on the display brightness though, which from my understanding should decrease with decreasing the pre-charge value. The noise also stays exactly the same. It seems I fail to pass the values to the SSD1306 correctly. I also tried changing the value in the Adafruit_SSD1306.cpp file:

Still no change. The noise stays exactly the same as well as the brightness. It's clear to me I'm doing something wrong, or I misunderstand the effect of changing the pre-charge value completely. I couldn't find anything in adafruit documentation on this matter. What am I doing wrong?

UPDATE:

I used other commands, such as setcontrast, which did have an effect on the display, so I did pass the values to the controller. It seems that changing the pre-charge value do not have much of an effect. On the other hand I discovered that I2C bus might be introducing the unwanted noise. When bypassing the data of clock line to ground via a capacitor the noise decreases. It seems I was looking for an issue in the wrong place.


texts:
Hello I'm trying to send some Structs such as:
typedef struct __attribute__ ((__packed__)) myohw_command_set_mode {
    myohw_command_header_t header; ///< command == myohw_command_set_mode. payload_size = 3.
    uint8_t emg_mode;              ///< EMG sensor mode. See myohw_emg_mode_t.
    uint8_t imu_mode;              ///< IMU mode. See myohw_imu_mode_t.
    uint8_t classifier_mode;       ///< Classifier mode. See myohw_classifier_mode_t.
} myohw_command_set_mode_t;

To another device via BLE using the Arduino BLE library.
I have the services and characteristics all set up correctly.
My problem is that arduino BLE .writeValue() function expects some specific formats and i'm not quite sure the best way to convert this struct to one of them.
  int writeValue(const uint8_t value[], int length);
  int writeValue(const void* value, int length);
  int writeValue(const char* value);
  int writeValue(uint8_t value);
  int writeValue(int8_t value);
  int writeValue(uint16_t value);
  int writeValue(int16_t value);
  int writeValue(uint32_t value);
  int writeValue(int32_t value);

What format should i use? And what is the best way to cast the Struct to the format?
Thanks,


texts: Why does the Arduino Uno WiFi network connection drop when requesting a page?

texts: I see frequent errors where the network connection to my Arduino Uno WiFi drops when I am requesting a web page. I wrote a simple REST server, and some of the pages will load as expected, but others will fail after loading half of the the text, and I notice that the network connection drops in the middle of these events. Why is the network connection dropping like this?


texts: Trying to get a servo motor to move to certain setpoints when a control potentiometer shows certain values

texts:
Here's my Code so far:

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

void loop() {
  float a;
  float angle;
  int setpoint;
  a = analogRead(A1);
  angle = map(a, 0, 1023, 0, 180);

  if ( (angle>0) && (angle<70) )
  {
    setpoint=50;
  }
  if ( (angle>70) && (angle<110) )
  {
    setpoint=90;

  }
  if ( (angle>110) && (angle<180) )
  {
    setpoint=130;

  }

  Serial.print(setpoint);
  Serial.print(",");
  Serial.println(angle);
}

I'm using an Arduino Genuino.

How can I get the servo motor to move to the setpoints and stop when the angle is between the eligible range?

just wanted to update showing how i solved this problem using the following code.

void setup() {
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
Serial.begin(9600);
}
void loop() {
float a;
float b;
float desired_angle;
float actual_angle;
float error;
float motor;
float setpoint;

a=analogRead(A1);
desired_angle=map(a,0,1023,0,180);

b=analogRead(A2);
actual_angle=map(b,125,920,0,180);

 if ( (desired_angle>0) && (desired_angle<70) )
{
  setpoint=50;
}
if ( (desired_angle>70) && (desired_angle<110) )
{
  setpoint=90;

}
if ( (desired_angle>110) && (desired_angle<180) )
{
  setpoint=130;

}

error=(setpoint-actual_angle);
motor=desired_angle/270*255;

if (error>0)
{
  digitalWrite(5,LOW);
  analogWrite(6,motor);
}
if (error<0)
{
  digitalWrite(6,LOW);
  analogWrite(5,-1*motor);
}

Serial.print(actual_angle);
Serial.print(",");
Serial.println(setpoint);

}


texts: want to get data from one IMU and Arduino simultaneously using I2c communication

texts:
I want to get data from an other Arduino and IMU using I2c communication and wrote a code given below but it is not working for me ,
#include<Wire.h>
// Define Slave I2C Address
#define SLAVE_ADDR 9

// Variable for received data
int x;

const int MPU=0x68;
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(115200);

}

void loop(){

  Wire.beginTransmission(MPU); //Send a request to begin communication with the device at the specified address
  Wire.write(0); //Sends a bit asking for register 0, the data register of the TC74 sensor

  Wire.endTransmission(); //this ends transmission of data from the arduino to the temperature sensor

//this now reads the temperature from the TC74 sensor
  Wire.requestFrom(MPU, 12);//this requests 1 byte from the specified address

while(Wire.available() == 0);
  AcX=Wire.read()<<8|Wire.read();
  AcY=Wire.read()<<8|Wire.read();
  AcZ=Wire.read()<<8|Wire.read();
  GyX=Wire.read()<<8|Wire.read();
  GyY=Wire.read()<<8|Wire.read();
  GyZ=Wire.read()<<8|Wire.read();

  Serial.print("Accelerometer: ");
  Serial.print("X = "); Serial.print(AcX);
  Serial.print(" | Y = "); Serial.print(AcY);
  Serial.print(" | Z = "); Serial.println(AcZ);

  Serial.print("Gyroscope: ");
  Serial.print("X = "); Serial.print(GyX);
  Serial.print(" | Y = "); Serial.print(GyY);
  Serial.print(" | Z = "); Serial.println(GyZ);
  Serial.println(" ");

/*Wire.begin(SLAVE_ADDR); //Send a request to begin communication with the device at the specified address
x= Wire.read();
Wire.end();
Serial.print("  angle  = "); Serial.println(x);*/
 delay(333);

}

need some suggestions to solve this problem .
code of arduino which is sending data is as follow
/*     Arduino Rotary Encoder Tutorial
 *
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *
 */

   // Include Arduino Wire library for I2C
  #include <Wire.h>

  // Define Slave I2C Address
  #define SLAVE_ADDR 9

 #define outputA 2
 #define outputB 3

 int counter = 0;
 int aState;
 int aLastState;
 int precounter;

 void setup() {
   pinMode (outputA,INPUT);
   pinMode (outputB,INPUT);

   Wire.begin();
   Serial.begin (115200);
   // Reads the initial state of the outputA
   aLastState = digitalRead(outputA);
 }

 void loop() {
   aState = digitalRead(outputA); // Reads the "current" state of the outputA
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
   if (aState != aLastState){
     // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(outputB) != aState)
     {
       counter ++;
     }
     else
     {
       counter --;
     }

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

     Serial.print("Position: ");
     Serial.println(counter);
     aLastState = aState; // Updates the previous state of the outputA with the current state

    Wire.beginTransmission(SLAVE_ADDR);
    Wire.write(counter);
    Wire.endTransmission();
 }


texts: Using Arduino to detect when a sensor is on and off and display time elapsed

texts:
I would like to know if I can use a pressure sensor with an Arduino. The code will detect when the sensor is on, will start a timer, stop when the sensor is off, and display the time elapsed.

Here is the code for the timer:

int main(void) {
  LARGE_INTEGER frequency; // ticks per second
  LARGE_INTEGER t1,t2; // ticks
  double elapsedTime;
  // get ticks per second
  QueryPerformanceFrequency(&frequency);
  // start timer
  QueryPerformanceCounter(&t1);
  //the code for sensorwill be written here
  QueryPerformanceCounter(&t2);
  elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
  printf("\nElapsed time : %lf ms.\n", elapsedTime );
  return 0;
}


texts:
I was trying to program my Arduino (along with a connected motor controller) to switch from cycle to cycle with this program.  It doesn't seem to work however.  There's still plenty of storage space and dynamic memory, so those aren't the issue.  This is the program:

int EnablePin1 = 8;
int duty;
int period;
int cycle;

int PWMPinA1 = 11;
int PWMPinB1 = 3;
int PWMPinA3 = 6;
int PWMPinB3 = 5;

const byte CPin1 = A0;

int CRaw1;
void setup() {

    Serial.begin(9600);

    pinMode(EnablePin1, OUTPUT);

    pinMode(PWMPinA1, OUTPUT);
    pinMode(PWMPinB1, OUTPUT);
    pinMode(PWMPinA3, OUTPUT);
    pinMode(PWMPinB3, OUTPUT);

}

void loop() {
    digitalWrite(EnablePin1, HIGH); //enable the board
    for (duty = 0; duty <= 255; duty += 15)
    {

        analogWrite(PWMPinB1, 0); //Set pinB to 0, when speed is written to pinA

        analogWrite(PWMPinA1, 255);
        delay(850);
        if (PWMPinA1 == 11)
        {
            PWMPinA1 = 3;
            PWMPinB1 = 11;
        }
        else
        {
            PWMPinA1 = 11;
            PWMPinB1 = 3;
        }
   }
   analogWrite(PWMPinA1,0);//end at max speed
   analogWrite(PWMPinB1,0);
   CRaw1 = analogRead(CPin1);

   Serial.println("Feedback");

   Serial.print(CRaw1);

   delay(2000);
   //analogWrite(PWMPinB3, 0);
   for (duty = 255; duty >= 0; duty -= 51) // ramp down speed
   {
       //analogWrite(PWMPinA1, duty);
       analogWrite(PWMPinB3, 0);
       analogWrite(PWMPinA3, 255);
       delay(period);
       //delay(cycle);
       if(PWMPinA3 == 6)
       {
           PWMPinA3 = 5;
           PWMPinB3 = 6;
           //period = 850;
       }
       else
       {
           PWMPinA3 = 6;
           PWMPinB3 = 5;
          //period = 2500;
       }
   }
   analogWrite(PWMPinA3, 0); //set to 0 speed
   analogWrite(PWMPinB3, 0);
   delay(2000);

   digitalWrite(EnablePin1, LOW);// Toggle enable to reset the power chips           if we have had an overcurrent or overtemp fault

   for (cycle = 1000; cycle < 9000; cycle += 4000)
   {
       //cycle=period;
       period=cycle;
   }

 /*for (cycle = 2000; cycle <= 3000; cycle += 1000)
   {
       //cycle=period;
       period=10000;
   }*/
   for (cycle = 9000; cycle >= 1000; cycle -= 8000)
   {
       period=0;
   }

   //delay(2000);  // Swap pins to make the motor change direction

}//end main loop

I've also tried having the cycle loops be this:

 for (cycle = 0; cycle < 9000; cycle += 3000)
 {
     //cycle=period;
     period=cycle;
 }
 for (cycle = 9000; cycle >= 0; cycle -= 9000)
 {
     //cycle=period/3;
     period=cycle;
 }

But that didn't do anything (I can see what PWM pins are powered through LEDs, and the first attempt, the LEDs only lit up for 1 second and the 2nd, they didn't light up at all.


texts: XBee WiFi: Does it work on the Wireless Proto Shield?

texts:
I have been following this tutorial by sparkfun

https://learn.sparkfun.com/tutorials/internet-datalogging-with-arduino-and-xbee-wifi

and I have XBee Wifi but not the Shield of SparkFun. I have the Wireless ProtoShield which is provided by Arduino.cc

I wonder if both are compatible with each other?
Thank you in advance.


texts: Moving cursor on LCD and changing highlighted value

texts:
I have the code shown below. The goal is to change the value of hours, minutes or seconds based on where the cursor is placed.

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
    int hours = 11;
    int minutes = 11;
    int seconds = 11;
    lcd.setCursor(0,0);
    lcd.print(hours);
    lcd.print(":");
    lcd.print(minutes);
    lcd.print(":");
    lcd.print(seconds);
    lcd.noBlink();
    delay(300);
    lcd.blink();
    delay(300);

    if (buttons & BUTTON_RIGHT) {
      move cursor right;
      if(lcd.setCursor == lcd.setCursor(0,3) {
        minutes += 1 }

}

I though of a way to do this. I would have three variables and print each of these out with a default value. With the use of the buttons, the user should be able to move the blinking cursor to hours, minutes or seconds, and increase or decrease the value of the variable.

I would do this by seeing what location the cursor is at. For example, if the cursor was on minutes, I would write something like if(lcd.setCursor == lcd.setCursor(0,3) or lcd.setCursor == lcd.setCursor(0,4)) { minutes += 1}.

Of course these functions don't exist, so I am wondering what I can do to move a cursor and check its position.

Thanks in advance


texts: Why can't I read anything but Pin 0 of PORTC?

texts:
So I am working on this lab for my Embedded Systems class, but I can't seem to read anything but the first bit of PORTC.  What's even weirder is that if any of the pins go low the first bit will go to 0, while all the others stay at 0 no matter what.

Here is my code:

 /*
 * Lab_4A.c
 *
 *  Reads the value of one distance sensor
 *  and reports if light/dark to the LCD.
 *
 *  Created on: Sep 24, 2014
 *  Author: Austin R. Bartz
 *
 *  LCD Connections:
 *  E   - PB4 (Digital 12)
 *  RS  - PB5 (Digital 13)
 *  R/W - GND
 *  Data 4,5,6,7 - PD4,5,6,7 (Digital 4,5,6,7)
 *
 *  Sensor Connections:
 *  Sensor 8 - PC0 (Analog A0)
 *  Sensor 7 - PC1 (Analog A1)
 *  Sensor 6 - PC2 (Analog A2)
 *  Sensor 5 - PC3 (Analog A3)
 */

#include <avr/io.h>
#include <inttypes.h>
#include <MSOE/delay.c>
#include <MSOE/bit.c>
#include <MSOE/lcd.c>
#include <user/initPorts.c>
#include <user/readPorts.c>
#include <user/writePorts.c>

void printBinaryLCD(uint8_t);
uint8_t readSensors();

int main(void)
{
    lcd_init();
    lcd_clear();
    while(1)
    {
        uint8_t val = readSensors();
        printBinaryLCD(val);
    }
}

void printBinaryLCD(uint8_t val)
{
    lcd_home();
    uint8_t A = ((PINC & (1<<3)) == (1<<3));
    lcd_print_uint8(A);
    lcd_goto_xy(1,0);
    uint8_t B = ((PINC & (1<<2)) == (1<<2));
    lcd_print_uint8(B);
    lcd_goto_xy(2,0);
    uint8_t C = ((PINC & (1<<1)) == (1<<1));
    lcd_print_uint8(C);
    lcd_goto_xy(3,0);
    uint8_t D = ((PINC & (1<<0)) == (1<<0));
    lcd_print_uint8(D);
}

uint8_t readSensors()
{
    DDRC = 1;
    PORTC = 1;
    delay_us(10);
    DDRC = 0;
    PORTC = 0;
    delay_ms(1);
    return PINC;
}

Any help would be much appreciated!


texts: Arduino: Reading Multiple registers in a single slave device

texts:
I have a single slave device lets call it (Address_slave) and that slave device  has 15 registers(Address_1, Address_2,..., Address_15).

Is there a way to read a specific one of these registers with an Arduino MEGA2560?


texts: Arduino Uno ADCH register stuck at 255 when read from ISR

texts:
I'm working on a project that will essentially become an oscilloscope in the long run. I am following this guide. My code is uploaded here for more reference.

In my .ino file I have called functions to set up register such that I have a timer ISR called at a frequency of 100 KHz, and an ADC clock rate of 2 MHz. The ADC is also set so that the result is left shifted so ADCH contains an 8-bit result. In a separate .h file I have an ADC ISR that looks like this:

ISR(ADC_vect)
{
  // Read 8-bit conversion result from ADCH.
  uint8_t byte0 = ADCL;
  uint8_t byte1 = ADCH;

  data_byte = byte1;
  flag = true;
}

The loop() function is the following:

void loop()
{
  if (flag == true)
  {
    //Serial.println("ISR HIT");
    Serial.println(data_byte);
    flag = false;
  }
}

So, when the ISR is called the flag is set to true, and in the loop() function I am notified with an "ISR HIT" printed on the serial monitor, this operation is successful.

However, I also have a volatile global variable in my .ino function called data_byte (also declared as an extern in the .h file) that I set byte1 to. When byte1 is printed to the serial monitor the result is:

255
255
255

Any ideas on why the value of ADCH is stuck at 255? My hardware is simply a light sensor connected to pin A0, 3.3 V, and GND.


texts:
Hello folks,
              I am using G1/4 Pressure Transmitter Sensor 0-1.2 MPa sensor can you guide for programming part.The conversion from bar to pascal  or bar to Mpa or pascal to psi.Though I am new to it. Plz guide me .


texts: Sending and receiving different types of data via I2C in Arduino

texts:
I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.

In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.

here is the code for the master

#include <Wire.h>

const int SLAVE_ADDRESS = 8; //Slave arduino ID
int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer.
void setup ()
{
Wire.begin ();
Serial.begin (9600);  // start serial for output
}  // end of setup
void loop()
{
Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8

for(int i=0;i<3;i++)//organizes the data from the slave in the table
{
int c = Wire.read(); // receive a byte as character
table[i]=c;
}
//displays the data
 Serial.print('\n');
   Serial.print(table[0]);
    Serial.print('\t');
   Serial.print(table[1]);
    Serial.print('\t');
   Serial.print(table[2]);
   Serial.print('\n');

delay (500);

// transmit just this variable to the slave
int Work=1;
Wire.beginTransmission (8);
Wire.write (Work);
Wire.endTransmission ();
}

here is the code for the slave

#include <Wire.h>
int table[]={0,0,0};
int Work=0;

void setup() {
Wire.begin(8);                // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
Wire.onReceive(receiveEvent); // register event
}

void loop() {
int x=120;
int y=1200;// gets converted to an strange # because is larger than 255
int z=3;
  table[0]=x;
  table[1]=y;
  table[2]=z;
}

void requestEvent()
{
  uint8_t Buffer[3];
  Buffer[0]=table[0];
  Buffer[1]=table[1];
  Buffer[2]=table[2];
  Wire.write(Buffer,3);
}

void receiveEvent(int howMany)
{Work = Wire.read();}


texts:
I have a question regarding how the read function works in Software Serial.

recv reads the bits a receiver picks up into a serial buffer. than read returns a uint8_t. However, when i set read() equal to a variable and print it, it doesn't necessarily always print out a byte.
For instance:
int x = rx.read(); //if the read is supposed to read 60, x prints 111100
int x = rx.read(); //if the read is supposed to read 226, x prints 11100010

How come the first statement doesn't print 00111100?

Sorry, i realize this might be a very dumb question. I looked into the software serial library, and couldn't identify what I'm missing.


texts: How can I send integer from arduino to another arduino by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)?

texts:
I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules.
For transmitting I use the library VirtualWire and It works very well for this code:

#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[7] = {'h','e','l','l','o',' ','!'};
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  delay(1000);
}

I was wondering if I want to send some string or int data how I can do that.
I tried to use it for string data but I couldn't because the Input of function vw_send(...) is char and I couldn't use int or string.
finally I run this code:

#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx(); // Wait until the whole message is gone
delay(1000);
}

and I could send Hello there !, but I'm looking for the correct way for sending string and int.


texts: Reprogramming a specific slave from the master ATTiny 85 (connected to IDE)?

texts:
Given that every ATTiny connected already has a bootloader (micronucleus) installed, here's my theoretical chain:

Computer > Master ATTiny (Connected via USB) > ATTiny Slave A > ATTiny Slave B

Is it possible to flash an individual slave (say, slave B) with new software without replicating it to all of the other slaves, or altering the master?

Can this be done with the normal MISO/MOSI/SCK/RESET method?

I've done some research (Programming multiple ATMegas/Arduinos at once) but I'm not looking for a batch flashing method; I want to upload custom programming to a single slave.

Note: I'm not trying to pass data between the master and the slaves. What I want is to reprogram the slaves from a single USB connection. It's also important that each slave has a fixed identity so I know exactly which one I'm flashing every time I boot the "system".

Disclosure: I'm an arduino novice and programming intermediate. This is my first project utilizing serial communication.


texts:
I have a seemingly simple problem that seems to be popular, but after searching several forums I still have not found the answer: How do you use a class inside of another class?

I have simplified my problem:

class A {
  const int pin;
  public:
  A(int attachPin) : pin(attachPin) {
  }

  void setup() {
    pinMode(pin, INPUT_PULLUP);
  }
};

class B {
  A myA;
  public:
  B(int a_attach) : myA(a_attach) {
  }

  void setup() {
    myA.setup();
  }
};

B test;

void setup() {
   test.setup();
}

void loop() {
}


texts: Transistor as switch for signal and high current buzzer

texts:
I'm a newbie in transistor switching.

I have PIR sensors with C and NC onboard. NC is 12 V signal that I need to switch transistor (bipolar?) to emit 3.3 V (collector connected to 3.3 V).

VCC equals 3.3 V. PIR is pin on ESP32.

Can you tell me if this circuit is okay or does it need additional edits?

Note: Q3, Q4 transistor number is random, if you can offer me suitable transistor I would be glad.

Next circuit:

ESP32 pin "ALARM" is connected to transistor (MOSFET N channel) base.

ALARM as device is connected to 12 V, required 300 mA to run and I need transistor to switch circuit. Relay is awful.

Is this circuit correct?
Do I need any additional edits?
Can you suggest me suitable transistor?
I don't know much about MOSFET shortcuts.

Third circuit I need is same as this but instead 12 V I need to switch 5 V.

I guess just to change MOSFET transistor?
Or use same as for 12 V?

Combined circuit schematic:


texts: esp8266 deep sleep timer slightly inaccurate?

texts:
I'm making a door open timer using a hall sensor and have a wemos d1 mini that uses a deep sleep to sleep for 1 minute after checking the hall sensor state and printing the value on the serial port. I'm using the Arduino IDE to monitor the serial output and have the Show timestamp option enabled so that I could time how long the device is running after it resets.  However, I'm getting output like this:

08:03:26.286 -> ^H⸮ȸ$RKx⸮⸮x⸮I⸮⸮696
08:04:25.454 -> HEA⸮⸮⸮d⸮⸮⸮⸮⸮⸮⸮696
08:05:24.681 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮696
08:06:23.915 -> ⸮DP⸮V⸮l⸮X⸮X⸮H⸮⸮694
08:07:23.178 -> ⸮A⸮K`E⸮M⸮⸮xxE⸮696
08:08:22.406 -> ⸮HlX⸮K⸮I|⸮⸮xE⸮693
08:09:21.703 -> ⸮⸮NI⸮ hlE⸮0⸮⸮E⸮694
08:10:20.978 -> 8H⸮JcD⸮M⸮⸮xxE⸮695
08:11:20.306 -> ⸮⸮NI⸮AhlE⸮ Op⸮⸮696
08:12:19.573 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮539
08:13:18.897 -> ⸮⸮OI⸮AhlE⸮⸮O⸮⸮538
08:14:18.196 -> HEA⸮⸮⸮d⸮⸮⸮⸮I⸮⸮539
08:15:17.561 -> ⸮dG⸮⸮⸮hLJ⸮@h⸮⸮(⸮539

The garbage output isn't what I'm asking about, it's the timestamps being created by the arduino ide. Since I sleep for 60,000,000 microseconds, I would assume that the second value of the minute would be slightly more each time. But as shown above, it becomes slightly less every time, as if it takes less than a minute. So what I'm wondering is if the sleep timer on these devices is not accurate enough to count on this or something else I should be considering like an inaccuracy in the IDE?  I only wanted to measure the uptime so that I could consider it for battery drain considerations, I don't really need a millisecond accurate timer for the functionality of the device.


texts:
void switch_led() {
bool SwitchReading = digitalRead(SWITCH);
if (SwitchReading == HIGH) {
Serial.println("Now pressed....");
state = state + 1;
if (state % 2 != 0) {
  digitalWrite(LED, HIGH);
  char data1[] = "{""LDRValue"": 88888888}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data1));
    client.println();
    client.print(data1);
    Serial.println("1.finish");
  }
  Serial.println("2.finish");
}
else {
  digitalWrite(LED, LOW);
  char data2[] = "{""LDRValue"": 1111111111}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data2));
    client.println();
    client.print(data2);
    Serial.println("3.finish");
  }
  Serial.println("4.finish");
}
delay(500);
   }
}

It works perfect for the first and second posts in both Arduino and API but at the third post it works fine on Arduino but it takes long time on the API(about 2 minutes to get the post). The fourth and the fifth posts also works fine but the sixth is same as the third. Knowing


texts: I'm writing an Arduino program to communicate with another module using RS485, so I need to control data flow with one pin. But when I set the pin to HIGH (line 88) it almost instantly falls (as you can see in the image, line 70). So my guess is that Arduino Serial.write() function is non-blocking, but I need it to be blocking so the flow control pin stays high during whole packet transmit. Please help. Thank you.


texts:
How many times we can rewrite code in
 XBEE, can we write code more than one or once a code is written it cannot be overwritten


texts: Is it possible to use Wi-Fi as a wireless connection to my Arduino/Windows PC LAN without using the internet

texts:
My Situation and Problem:

I am wanting to put together a system to help monitor the soil moisture content in my garden and a small heated greenhouse I use in the winter. Also, In the near future I would like to build a system to remotely monitor the nutrients in my soil and other grow media, and have it accessible through my computer using a system similar to the one I'll have monitoring the moisture levels. In both situations I am growing nearly all crops hydroponically.

I have found several instances of people doing this by having the information posted to a service provider's website. Then it is possible to access the information by way of email or connecting in some manner to the service provider's site.

I plan to store the data in the cloud, but where I live we get internet access through satellite dish or land based re-transmission sites. So, I am planning to keep all gathered data in "The Cloud" manually, once received when I turn on my computer. I even have to use a booster device in my house to get dependable cell phone service. My land line telephone service provider doesn't offer high speed internet service, so I don't presently use a smart phone. I recently read a news article talking about a similar, though more widespread situation in Australia. In Australia they call it the tyranny of distance.

In addition to my garden and greenhouse, I have several other ideas for using Arduino to gather data using wifi and do any number of other things, and most of these ideas include accessing the gathered data through my computer connected to an Arduino device as required. It would certainly be helpful if anyone would be willing to share any ideas or point me toward inexpensive solutions.

Thanks for your kind consideration.


texts: GSM shield 2 - Fully erase memory buffer

texts:
I would love to get real developers' input regarding the following issue as I've been spinning my head around it for a while now.

What I'd like to do

My program receives SMS containing simple instructions. When a SMS is received, the code will run according to the instruction. In the mean time, other SMS can be received by the modem[1].

  I would like my program to ignore any instruction received while it was busy doing something, and therefore I'm looking for a way to delete any SMS received before the arduino finished doing what it was doing.

What I'm having trouble with is the sms.flush() function. This function is available from the GSM.h library, which is bundled with the Arduino IDE by default.

and here comes the first glitch: the flush()function reference page states that it "clears the modem memory of any sent messages once all outgoing characters have been sent". So it seems at first that flush() would only work for outgoing messages...
...but in the mean time, the official sketch for SMS reception (ReceiveSMS) does indeed use flush() to delete received SMS.

So for me, flush() really works both for outgoing and received SMS. Am I right?

What I did

Here is how the program works:

The arduino receives a SMS and is asked to light a LED
It does as instructed
then sends a SMS back saying that the LED is ON.
The DeleteSMS function is triggered

Here is the code:

void DeleteSMS(){
    int MessageQtt = 0;
    Serial.print(F("["));
    do{
        sms.flush();
        MessageQtt++;
    } while (sms.available() > 0);
    Serial.print(MessageQtt);
    Serial.print(F(" message(s)"));
    Serial.println(F(" have been deleted]\n"));
}

This function is therefore called at the end of the Arduino operations. With it, I wanted to force the Arduino to delete not only the first SMS received as well as the one sent back, but also any SMS received in the mean time.

But it doesn't work and I can't really find out why.

My devices

Arduino UNO
GSM Shield 2
local (France) provider SIM card

Thanks all in advance for your input...

(by the way: if someone could tell me where to find the GSM.h file, I could mess with it to see how things work...)

[^1]: From what I've learned, any SMS received while the modem is turned off or the Arduino busy doing something else will be stored in the memory buffer, but I can't really retrieve my source on that one.


texts: Not getting pure color while using the FastLED with WS2812b

texts:
I am working with the LED strip WS2812b and FastLED library, currently I have only 3 LEDs connected in such a way that the first 2 receive a color (say green) and the last one receives another one (say blue).

The problem is that by putting the color (blue) on the last LED, the other two (currently only in green) also take a portion of blue, preventing it from being a pure (green) color. It happens with any combination of color.

I leave the piece of my code referring to the LED strip:

#include "FastLED.h"
#define NUM_LEDS 3
#define DATA_PIN 2

//Variables declaration...
....

void setup() {
  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
.....

  }

void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
      if (digitalRead(pinNo+3) == HIGH){
        leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
           FastLED.show();
            }
        }

  }

I already change the pin for where I put the signal for the LED strip, I try to change the type of LED strip

FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS)
FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS)
FastLED.addLeds<WS2812, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS)

without any success...

Can anyone point me in the rigth direction?

Edit: actually, the first LED of the strip is flashing, not in the way of the Blinking example, but I can see a little flashing.


texts: IoT gabage monitoring system with my own Android application

texts:
I'm developing a device system in our campus - my aim is to provide three IoT smart garbage containers that will get the fill level (to determine the space of garbage inside and to inform the garbage collector if the garbage is empty, not yet full and full), temperature and humidity from the garbage bin and will send the information to my application that I'm going to develop.

I don't know how I can connect these three IoT devices which are a fair distance from each other. I know it should be wireless though I can't figure out the exact Arduino device to provide connection to my mobile application.


texts: I've been trying to use interrupts to control a quadrotor with a tx/rx to no success. I'm using an arduino mega as my control board. I have successfully read a singe channel using attach interrupt and PulseIn. I have also successfully read multiple channels with pulse but failed to do so with attach interrupt and pinchange int. Should I just go ahead and use PulseIn


texts: Reading a flash ROM chip (M45PE20) through SPI with an ATMEGA 2560 -- output only FF's

texts:
I'm trying to communicate through SPI to a Flash ROM chip (M45PE20) with an ATMEGA 2560. I'm looking to read the data off the chip, but the output I'm getting is nothing but FF's. I've checked my wiring and everything looks okay on that end, I also don't have a scope to probe the output unfortunately.
I've the crude code below:
void setup() {
  Serial.begin(9600);
  pinMode(SS, OUTPUT);
  digitalWrite(SS, HIGH);
  SPI.begin();
}

void loop() {
  Serial.println("Starting");
  Serial.println("Waiting 1s");
  delay(1000);
  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));

  digitalWrite(SS, LOW);
  Serial.println(SPI.transfer(0x03));
  Serial.println(SPI.transfer(0x00));
  Serial.println(SPI.transfer(0x00));
  Serial.println(SPI.transfer(0x00));
  for (int i = 0; i < 16384; i++) {
    Serial.print(i * 32, HEX);
    Serial.print(" ");
    for (int j = 0; j < 32; j++) {
      Serial.print(SPI.transfer(0xFF), HEX);
      Serial.print(" ");
    }
    Serial.println();
  }

  Serial.println();
  digitalWrite(SS, HIGH);
  delay(500);
  SPI.endTransaction();
  delay(5000);
}

Link to datasheet: https://drive.google.com/file/d/1_Zlg-hb5B08u7_m_N4_addmmjyv_nANS/view?usp=sharing
Picture of specific read command from datasheet:


texts:
in an Arduino sketch a user is invited to input a number representing a time in the format HH:MM,  this number is to be added at the end of an ordered and limited sequence of times

--the first input (lower limit) can be any time within the 24 hours,

--the upper limit is calculated as lower_limit+period; with period being 1,2,3,4,6,8,12 or 24 hours,

--and to be accepted, the input must verify that it is chronologically after the previous element, and that it's within the given period;

for example if first element is 20:00 and the period is 8, the upper limit will be 20+8=28 wich is 04:00; both 21:00 and 03:00 are accepted, where'is 19:00, 05:00, 09:00, 17:00, ... are rejected.

without any information on the 'day', i did not find any suitable algorithm, and none of the available Arduino libraries is useful in this case.

any link, or tip,...


texts: Digital Reading from a array without using the exact element

texts:
Is it possible to read a digital input from an array without using the exact element? Such as

   while(digitalRead(myButtonArray[i]))
     digitalWrite(myLEDArray[i], HIGH);

Reading the myButtonArray one by one and turning on the led one by one doesnt make for clean written code. The following is just an example code. When button on pin 2 which is element 0 is pressed turn on led on pin 7 and turn off when released. When button on pin 3 is pressede turn on led on pin 8 and turn off when released and continue on in the same fashion with the rest of the buttons and leds as well.

 int myButtonArray[] = {2,3,4,5,6};
 int myLEDArray[] = {7,8,9,10,11};

 void setup() {
   for(int i = 0;i<5;i++){
     pinMode(myButtonArray[i], INPUT);
     pinMode(myLEDArray[i], OUTPUT);
   }

 }

 void loop() {
 while(digitalRead(myButtonArray[0]))
      digitalWrite(myLEDArray[0], HIGH);

 while(digitalRead(myButtonArray[1]))
      digitalWrite(myLEDArray[1], HIGH);

 while(digitalRead(myButtonArray[2]))
      digitalWrite(myLEDArray[2], HIGH);

 while(digitalRead(myButtonArray[3]))
      digitalWrite(myLEDArray[3], HIGH);

 while(digitalRead(myButtonArray[4]))
      digitalWrite(myLEDArray[4], HIGH);
 }


texts: Making a PID Controller for BAR 30 pressure sensor

texts:
I am having issues with my PID controller  for a BAR 30 depth sensor. The issue that I have is my ESC have two initial start up { 1500 - 1900} is min - max respectively clockwise and { 1500-1900} is max respectively counter clockwise.
What I want is for me to set a depth and I can submerge to a certain depth and lock in at that certain depth.

#include <PID_v1.h>
#include <MS5837.h>
#include <Wire.h>
#include <Servo.h>
MS5837 sensor;
Servo vertical_thruster1;

// Variables

float current_depth ;
float set_depth = 0.50 ; //  depth u wish to go in meters
float PID_error = 0;
float previous_error = 0;
float elapsedTime,  Time , timePrev;
double pwmvertical_thruster1 = 1440;

int s;

float PID_value = 0;
float PID_p = 0;
float PID_d = 0;
float PID_i = 0;
//PID constants
float kp = 100;
float ki = 0.003;
float kd = 5.2;

void setup() {
  Serial.begin(9600);
 vertical_thruster1.attach(4);
   vertical_thruster1.writeMicroseconds(1500);

 Time = millis ();

 ///Bar 30 Configuration

  Serial.println("Starting");
  Wire.begin();
 while (!sensor.init()) {
Serial.println("Init failed!");
Serial.println("Are SDA/SCL connected correctly?");
Serial.println("Blue Robotics Bar30: White=SDA, Green=SCL");
Serial.println("\n\n\n");
delay(2000);
  }
  sensor.setModel(MS5837::MS5837_30BA);
  sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
}

void loop() {

///*
// First read the current value of the depth sensor
sensor.read();
current_depth = sensor.depth();

timePrev = Time;
Time= millis();
elapsedTime = ( Time - timePrev) / 1000;

// calculate the error between the set depth and current depth
 PID_error =  set_depth - current_depth ;

 // Calculate the P Value
 PID_p = kp * PID_error;
   Serial.print("PID_p: ");
    Serial.print(PID_p);
    Serial. println ( "\t\t");
// Calculate the i value in a range on +-0.3

 if (-0.2 < PID_error < 0.2)
 {
  PID_i = PID_i + (ki * PID_error);
 }
Serial.print("PID_i: ");
Serial.print(PID_i);
Serial. println ( "\t\t");
// Calculate the d value
 PID_d = kd*((PID_error - previous_error)/elapsedTime);
Serial.print("PID_d: ");
Serial.print(PID_d);
Serial. println ( "\t\t");
// The total PID value
PID_value = (PID_p + PID_i + PID_d) ;

// range for the blue robotics esc

if ( PID_value < -150)
 {
 PID_value = -150;
  }
  if( PID_value >150)
  {
  PID_value = 150;

  }
  Serial.print("PID_value: ");
  Serial.print(PID_value);
  Serial. println ( "\t\t");
 // calcualte the pwm

 s =  (pwmvertical_thruster1 + PID_value  );
 if(s < 1350)
{
 s= 1450;

}
else if(s> 1650)
{
  s=1550;

}
  Serial.print("Depth: ");
  Serial.print(sensor.depth());
  Serial.println(" m");
  Serial.print ( "Speed s  ");
  vertical_thruster1.writeMicroseconds(s);
  Serial.print( s) ;
  Serial. println ( "\t\t");
  previous_error = PID_error;
  //  */
  delay(300);
 }


texts: Arduino UNO + ESP8266 WiFi Relay by LC Technology

texts:
I have Arduino Uno, and recently obtained ESP8266 WiFi Relay by LC Technology. I tried to look up some information about that on the net, but all the answers / suggested solution didn't work for me. Let me briefly explain the problem.

I have connected this module to arduino in a very simple way:

TX -> pin 7
RX -> pin 6
5V -> IN +
GND -> IN -

Simple code:

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

#define TxPin 7
#define RxPin 6

SoftwareSerial ESPrelay(RxPin, TxPin);

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

    readRx();

    ESPrelay.println("AT");
    readRx();
}

void loop() {
    Serial.println(ESPrelay.read());
    // this above is constant -1
}

void readRx() {
    String msg = "";
    while (ESPrelay.available()) {
        char rxByte = ESPrelay.read();
        msg += rxByte;
    }
    Serial.println(msg);
    delay(500);
}

I can see WiFi AP created by the module - so I think module itself works fine - communication between Arduino and module is somewhat broken.

I tried all different AT commands, but none of them seems to take an effect (tried switching modes and connecting to home WiFI, but no luck) also, no response is returned. Could someone try and help me debug this issue?

I tried changing 9600 to 115200 when communicating, but no luck with this either.


texts: Serial communication stops when I connect the tx cable

texts:
I'm using the apc220 rf modules. Now I'm having the following problem:

My receiving arduino uno only receives data when the tx pin on the arduino (rx pin on the rf module) is disconnected. As soon as I connect the tx pin my serial monitor receives only the value 0.

Is my rf module broken, or can someone help me with this?


texts:
I'm trying to make the ATTiny85 work with the MMA7660 accelerometer, so far, without any success. Google search for "ATTiny85 MMA7660" gives poor results, and I'm not sure it has been done at all, at least publicly, so I thought I'll try my luck here.

What I've tried is using the TinyWireM library, in different combinations. The last one is based on the MMA7660 Arduino library, specially adjusted to the TinyWireM, and taken from this post in Arduino forums (direct link to download).

The SCL is connected to PB0 and SDA to PB2, with 5k ohm pull-ups (I know that the recommended is 4.7k but this is what I have available, and I assumed it shouldn't make much difference).

I am using the Arduino IDE v1.5.6, which works successfully with other non-I2C attiny projects I have.

As for the final code I am using the .pde example that comes with the MMA7660, altered to use SoftwareSerial:

#include <TinyWireM.h>
#include <MMA7660.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(-1,4);

void setup()
{
  mySerial.begin(9600);
  MMA7660.init();
}

void loop()
{
  int x,y,z;
  delay(100); // There will be new values every 100ms
  MMA7660.getValues(&x,&y,&z);
  mySerial.print("x: ");
  mySerial.print(x);
  mySerial.print(" y: ");
  mySerial.print(y);
  mySerial.print(" z: ");
  mySerial.println(z);

}

The current problem with the above code is that the pointers just dump some memory without making any sense. If I try to see what TinyWireM.receive() command returns, values are 216 for all three variables. This is true even when I disconnect the MMA7660 from the prototyping board...! so I assume the problem is with the I2C itself, not working properly. The actual I2C address for the MMA (0x4C) and other relevant code is in MMA7660.cpp.

Any ideas?... Unfortunately I don't currently have another I2C device to examine the health of this protocol with my ATTiny85, so any experience you might have with this sort of configuration will be blessed.

EDIT: I marked dvlabsllc's answer as accepted answer since it gave me the right direction to pinpoint the issue further down the library path. I have opened a new question regarding TinyWireM library here.


texts:
This question is quite clear. What are the differences between an int, an uint8_t, and an uint16_t. I know it has to do with bytes and memory but can someone clarify me a bit?

Things I want to know:

1- How much memory does each take.

2- When to use what.

3- In the end of the day, are they that different?


texts: Purpose of this resistor in Arduino Nano schematic

texts:
I was looking at the Arduino Nano's schematic and noticed a resistor that seems to be pointless (RP2C on this picture).

Also there is numbers 6 and 3 on it, does it mean that resistor is connected to pins 6 and 3 on FT232 or to the same pins on Atmega328?


texts: Using RTC DS3231 + Arduino UNO to calculate time lapsed

texts:
I am a beginner with no coding background.
I am trying to figure out an alarm that tells people how long they have been sitting on their chair.
The concept is very simple when the person would sit in his chair it will trigger an event ( maybe a button press) which should trigger the counting of time. if the time exceeds a limit (let's say an hour) a buzzer will go off. The only way to stop the buzzer is to stay away from the chair for let's say a minute.
I don't know how to start writing this code, especially how do I make this time counter start with this sitting action ( which might press a button).
Its for my class project so any help is highly appriciated.


texts: How to interface DS Lite Touch Screen with Arduino

texts:
I recently tore down my old DS Lite which wasn't working. The screens and speakers were still functional, so I decided to mess around with it. I have a working DS touch screen and an Arduino Uno. How would I be able to interface with the screen? The ribbon cable is still intact, I've seen the Sparkfun adaptor to work with the touch screen aspect, but how can I display an image on the screen? I would assume it's the same as a TFT screen, but I'm not certain... Thanks for the help!

EDIT: I don't currently have a shield to connect TFT screens. so a good shield/adaptor recommendation would be helpful!


texts: How to receive data from my server database to a variable in my Arduino?

texts:
I am learning to work with the client - server communication. I am able to communicate with my server and able to store values in the table. But I want to receive one of the specific data from the database.

Here I want to get the 'abc' value from the 'Current' column to store in a variable in my Arduino.

Below is the code that I have done until now. I would be really happy if you could solve the problem.

Here is my database structure

---------------------------------------------------
| Device |  Previous |  Next |  Distance |  Current|
---------------------------------------------------
|katup123| xyz       | abc   | 2.600     | abc     |
---------------------------------------------------

Here is my PHP code:

locator.php

<?php
$con=mysqli_connect("your_domain.com","peter","abc123","locate");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT Current FROM locate WHERE Device='katup123'");

while($row = mysqli_fetch_array($result)) {
  echo $row['Current'];
  echo "<br>";
}
?>

Here is my Arduino code:

// Include the GSM library
#include <GSM.h>
#define PINNUMBER ""
// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APNgpsll
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password
// initialize the library instance
GSM gsmAccess;
GSMClient client;
GPRS gprs;
// URL, path & port (for example: arduino.cc)
char server[] = "your_domain.com";
char path[] = "/locater.php";
int port = 80; // port 80 is the default for HTTP

void setup() {
  Serial.begin(9600);
  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;
  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected) {
    if((gsmAccess.begin(PINNUMBER)==GSM_READY) & (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
      notConnected = false;
    else {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  Serial.println("connecting...");
}

void loop() {
  char result [20];
  Serial.print(" Connecting to server Database ");
  if (client.connect(server, port)) {
    client.print("GET /locator.php?");
    Serial.print("GET /locator.php?");
    client.println(" HTTP/1.1");
    Serial.println(" HTTP/1.1");
    client.println("Host: www.your_domain.com");
    Serial.println("Host: www.your_domain.com");
    client.println("User-Agent: Arduino");
    Serial.println("User-Agent: Arduino");
    client.println("Accept: text/html");
    Serial.println("Accept: text/html");
    client.println("Connection: close");
    Serial.println("Connection: close");
    client.println();
    Serial.println();
    Serial.println("\nCOMPLETE!\n");
    client.stop();
  } else {
    Serial.println("connection failed");
    Serial.println("\n FAILED!\n");
  }
  delay(5000);
}

Here I want to store the 'abc' value to my 'result' variable. I don't know how to do it.


texts: Is it possible to implement old AVR library onto arduino (specifically, NodeMCU esp8266)

texts:
I am a Computer Engineering Undergrad, currently in a cryptography(computer security) course, and I was assigned to do projects about implementing µNaCl library onto Arduino. I currently own a nodemcu esp32 which serves as my device, and I have been searching for µNaCl libraries on the web, but the only thing I found was µNaCl library for AVR devices (based on the makefile of the library, i can see that it's designed for atmega128 and atmega2560). So my question is, is it possible to implement some library meant for AVR on my nodemcu? I mostly do my job with arduino libraries, and have never experimented with avr libraries on arduino, and especially considering my nodemcu is not using atmega-based architecture either, I kinda doubted it. And is the solution to my problem (if it's not possible to use avr based library on arduino) to go purchase a atmega128/atmega2560 and code on atmel studio?
Library: https://munacl.cryptojedi.org/atmega.shtml
Sorry for the long question, kinda desperate here.


texts: I'm doing a project with my friends and I need to import some external data, which changes, to Arduino. I'm using python to use opencv, take photos and count the faces in that photo. And I need to use that number in my Arduino code. How can I do this?


texts: need to compare if a byte is less than 80 hex

texts:
I am using an infrared sensor called OTI301. In its data sheet it says that in order to obtain object temperature and ambient temperature values I need to extract the binary information from the sensor and use the binary information in given formulas. I have done all that but for some reason I am not getting the right values for the object temperature. The ambient temperature seems to work well but when I put a hot object, more than 320 F, the formula returns a random negative number. Also the the sensor can go up to 780 F so I know the temperature has not been capped. Please see pictures for important data sheet information, or here are the links for the complete data sheets
https://drive.google.com/file/d/1XMRDCNzY3fn0q6lkGejs5D-pqksfRuZ8/view?usp=sharing.
https://drive.google.com/file/d/1mmdkHkNbwC5VgQxGMrq07XolajNvgBkN/view?usp=sharing. Lastly, here is the part of the code where I extract the information and apply formulas.

     void loop()
 {
   if (Wire.read()) // On success, read() will return 1, on fail 0.
   {
     buttonState = digitalRead(button);
     //Serial.println(buttonState);
     Wire.beginTransmission(DEVICE_ADDRESS);
     Wire.write(0x80);  // readout command
     Wire.endTransmission(false);
     Wire.requestFrom(DEVICE_ADDRESS, 6); // request 6 bytes
     uint8_t data[6];
     for (int i = 0; i < 6; i++) {
         data[i] = Wire.read();
     }

      //Calculate Object Temperature
     if(data[5] < 0x80) {
       TA = (data[3]+ data[4]*256+data[5]*65536)/200;
     }
     else {
       TA = (((data[3]+ data[4]*256+data[5]*65536)) - 16777216) /200;
     }

     //Calculate Ambient Temperature
     if(data[2] < 0x80) {
       TA = (data[0]+ data[1]*256+data[2]*65536)/200;
      }
     else {
       TA = (((data[0]+ data[1]*256+data[2]*65536)) - 16777216) /200;
     }


texts: How to set a timer for a function and be able to reset it in the middle of the process?

texts:
Hello me and my friend have to do an assignment for school but we need some help. We have to make a LED turn on and of with a button and a relay. But when I press the button the LED should be on for 10 minutes and then go off unless we press the button inside those 10 minutes then the LED should turn off. Then repeat this process when we press the button again.

const int relay = 6;
const int button = 5;
int stateold = 1;
int statenew = 0;
int LED = 0;

void setup()
{
  pinMode(relay,OUTPUT);
  pinMode(button,INPUT);
  time = millis();
}

void loop()
{
  statenew = digitalRead(knop);
  if(stateold==0 && statenew==1){
    if(LED==0){
      digitalWrite(relay,HIGH);
      LED = 1;
      }
    }
    else{
       digitalWrite(relay,LOW);
        LED = 0;
    }
  }
 stateold=statenew;

}


texts: Passing a long string from SoftwareSerial to Serial

texts:
I'm currently playing around with a GPRS shield on an Arduino Uno, for which I have to write raw AT commands over the SoftwareSerial. At the moment, I just want to be able to talk to the GPRS from my PC, so I've written a really basic program to send serial in two directions:

#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);

void setup()
{
  GPRS.begin(19200);
  Serial.begin(19200);
}

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

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

So the communication looks something like this:

         HW               SW
+----+ Serial +-------+ Serial +------+
|    |        |       |        |      |
|    +-------->       +-------->      |
| PC |        |Arduino|        | GPRS |
|    <--------+       <--------+      |
|    |        |       |        |      |
+----+        +-------+        +------+

This seems to work fine for shorter commands:

AT+CPIN?

+CPIN: READY

OK

But I'm really interested in doing a NETSCAN to see what networks are available. When I try it, I get this:

AT+CNETSCAN

------MOST SUITABLE CELL------
Operator:"YES OPTUS",MCC:505,75

And that's all. I pulled out a logic analyser to spy on the serial pins themselves, and it appears that the complete message is being sent back to the Arduino from the GPRS module perfectly okay - but for some reason, it gets cut off before it reaches my PC.

This is what the logic analyser sees over the SW (top two tracks) and HW (bottom tracks) serial lines:

So it appears that the entire GPRS response is being read by the Arduino before it starts to send anything back to the PC, and I assume that some sort of buffer has been overrun and I only get the start of the message.

So - how should I go about passing through long strings between serial ports like this? I assumed that using if (X.available()) instead of while would alleviate any issues with long strings (because it appears that this way the two serial ports should take turns with one byte at a time), but is that assumption incorrect?


texts: My Arduino Robot doesn't move, and it's the only thing that doesn't work

texts:
It will be simple. I started to look at the sketch of the Arduino Robot and just tried one, Disco_Bot, and uploaded it one the top board. The Arduino started to play some music and the name was on de LCD screen but he wasn't moving. Then i tried then sketch Wheel_Calibration. The information was on the screen but the Robot was supposed to move so that i could calibrate the speed. I was lost so I went on the Arduino page for the Arduino Robot (http://arduino.cc/en/Guide/Robot) and found nothing that could explain my problem . So now I ask you, can you please help me because iI have no idea on what i should do.

Chris


texts: Raspberry Pi 3B+ BLE communication to Arduino Nano 33 IOT

texts: I have an Arduino Nano 33 IOT and it uses BLE. I want it to talk to my Pi 3B+ and send all of its sensor data. I cannot figure out a way to do it using Python for the Pi and ArduinoBLE library for my Nano IoT. Is it possible?


texts: Arduino Yun not showing up in Windows or Linux [software issue?]

texts:
I've got my Arduino Yun (less than a year old) connected to my computer via a USB cable. The device seems to be on (that is, the lights are all on). However, the Arduino is not showing up in either the /dev/ttyACMx (linux) or COMx on my Windows boot. Does anyone have any suggestions for why this could be? I've tried to reset the Yun to factory settings by holding the WRT RST button for 30+ seconds, but that still didn't fix anything.

I'm afraid that I'm now looking at a bricked Yun; if this is the case, what could / should I do?

Thanks!

EDIT: I have the 1.6.0 version running. I'm indeed using a microUSB cable to connect to the arduino via USB. If I'm connected to the Arduino-90xxxxxxx wifi network, I can still push sketches to the arduino. However, I'm unable to see the arduino over serial, both in the IDE / terminal. The only port I see in the IDE is 192.168.240.1

EDIT2: I was able to see my Arduino Yun in the IDE again after flashing the blink sketch via wifi and resetting the 32u4. This makes me think that it's a software issue due to the sketch I'm pushing. Is there something that I could be calling which would make the Arduino unable to connect via serial?


texts: New Arduino Motor Shield Short Circuiting my board?

texts:
I just got this today, plugged it in my arduino, and the arduino light starts dimming until you cannot see it any more over the course of 5 seconds. The Computer disconnects the arduino when the light is off (Ding Dong Sound). I found pulling the VIN Connector Jumper/Power Jumper will stop the short circuit and work, but that defeats the purpose, as the board wouldn't even powered.

Here is the video:
YouTube

Is the motor board broken? If so in what way? are the wires on the board simply broken? Is it due to bad soldering?(I checked solder, looks fine).

Arduino Model: Arduino UNO by Elegoo
Motor Driver Model: L293D Driver Board
Ebay Listing For Item
(I tried using this with a MEGA also, would short it as well).


texts:
I have recently just built a custom arduino using the schematics found on their website. As awesome as this little processor is, I need more power. I have been thinking of making my own MCU, but wanted to know if it is possible to make them compatible with the arduino software. It would be very nice to not have to rewrite my existing programs.

If so, how would I go about doing that? If this is not a possibility (or just not a good idea for any reason), which language should I learn to start programming these upper level MCUs.

If I do have to start using a different language, what kind of software do I use to upload the code to these processors? And do they have the common features like Serial Monitor and Serial Plotter like the Arduino IDE does.


texts:
my arduino uno stopped working. It shuts off itself every time i plug it in. This golden thing is ovetheating.

Do i have to replace it or buy a new uno or what.


texts: I2C TinyWireS SEND: How to convert unsigned long to uint8_t array?

texts: How do you convert an unsigned long to a uint8_t array? I am interested in sending an unsigned long integer from an ATTiny85 to an Arduino Uno via I2C. The issue is with TinyWireS.Send() which can only send a var of type uint8_t. I believe the solution would be to use TinyWireS.Send() in an array?


texts: UART between arduino UNO and pc via USB not in sync

texts:
I connected my arduino uno to my system and then using serial tried writing and reading data but there is a problem which I found when I tried giving arduino crafted messages.
My arduino code is pretty simple.
void setup() {
  Serial.begin(115200);

}

void loop() {
  if (Serial.available() > 0) {
    String data = Serial.readStringUntil('\n');
    Serial.print(" You sent me: ");
    Serial.println(data);
  }
}

and my python code on my system
#!/usr/bin/env python3
import serial
import time

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)
    ser.flush()

    while True:
        string=input("Enter the string: ")
        ser.write(str.encode(string))
        line = ser.readline().decode('utf-8').rstrip()
        print(line)
        time.sleep(0.01)

Now this gives me ability to write instructions to my arduino but following sequences of communication occur
└──╼ $python3 serial_communication.py
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v
Enter the string: d

Enter the string: r
 You sent me: sd
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds
Enter the string: r
 You sent me: e
Enter the string:

Looking at them I understand that this might be a problem with my code or I am using the wrong protocol.


texts: Difference between WiFiClient and HttpClient

texts:
Apologies if this question appears to be too vague but I would like to know the key differences between these two clients.

While WiFiClient comes pre-loaded with Arduino IDE, HttpClient doesn't. Also, to send HTTP commands to a server (XML/JSON), which one to go for?


texts: #include  generates compile errors with no code

texts:
Consider the following (non)code example:
#include <stdatomic.h>

void setup()
{
  // Nowt.
}

void loop()
{
  // Nowt squared.
}

This generates compile errors for several lines of code in stdatomic.h, e.g.:
error: '_Atomic' does not name a type
 typedef _Atomic _Bool atomic_bool;
         ^~~~~~~

error: 'atomic_flag' does not name a type; did you mean 'atomic_load'?
 } atomic_flag;
   ^~~~~~~~~~~
   atomic_load

I've tried compiling it with the Arduino IDE for Uno. And I've tried godbolt.org with several compilers; some compile Ok; some don't.
Is there a way to get it to work for Uno? Which architectures support it?
What I would like to achieve is an atomic read/write of a struct, something like this:
#include <stdatomic.h>

typedef _Atomic struct
{
  int i;
  bool b;
  float f;
} Data;

void foo()
{

 Data d;// = {3, false, 1.234};
 atomic_init(&d, {3, false, 1.234});  // Some compile this; others don't.

 Data copy;
 copy = d;                // Compiles OK.
 atomic_store(&copy, d);  // Doesn't compile even with compilers that compile _Atomic. Syntax error? See Note 1.
}

Note 1:
error: no viable conversion from 'Data' (aka '_Atomic(struct (anonymous struct at <source>:5:17))') to 'struct (anonymous struct at <source>:5:17)'

 atomic_store(&copy, d);


texts: ESP8266 - 12F High consumption in led blink (with pictures)

texts:
My esp is consuming 180mA with a led blink. The same consumption happens when I put it in WIFI_STA mode with the WiFi.mode(WIFI_STA); function.
What should I do to reduce consumption? Used AMS1117 CI as tension regulator.

My code:

void setup() {
  pinMode(2, OUTPUT); // pin number 2 is on board blue led
}

void loop() {
  digitalWrite(2, LOW); // blue led highlight with LOW level
  delay(100);
  digitalWrite(2, HIGH);
  delay(100);
}

Why all this consumption?


texts: I recently created a pcb with the atmega32u4 to use it as a development board. The controller is connected to a micro usb port. Should I install the arduino bootloader instead of the deafult one? Or keep the default boot loader and find another way of flashing hex files? But bottom line what is the process to flash a hex file to the atmega32u4 via usb?


texts: Is this function subject to memory fragmentation?

texts:
I'm trying to understand if the following bit of code is subject to memory fragmentation.

Let's say I incrementally build a string within a function and I don't know how large the string should be.

String f() {
    String s = String("");
    s += "a"; // ...
    s += "bc"; // ...
    return s;
}

The String object does dynamic memory allocation internally, but s is on the stack, so once the function returns, the s object presumably deallocates and dynamically allocated memory is freed.

Before this happens, the String object to be returned must be copied from s. Since String objects hold internal data in dynamically allocated buffers, this means that the s internal buffer is allocated, then the return object internal buffer is allocated, then the s internal buffer is deallocated.

The return object internal buffer allocation is sandwiched between the s object alloc and dealloc.

To me, this implies that this will cause memory fragmentation. Am I reading this properly, or is this not the case? If so, does this also imply that functions like Serial.readString are also subject to memory fragmentation?


texts: I want to use my arduino to turn a light off for 16 hours and on for 8 hours. I know the general code, just using delays and the relay shield code as well. I want to know how accurate this will be? ( I tagged uno and leonardo, as I have access to both)


texts: Interaction between Analog Pins when measuring a DC voltage- a common issue?

texts:
Just set up a replacement "Piduino" - a RPi3 connected by USB to an Arduino Uno.  The previous one was the victim of a Diet Big Gulp - spilled on the voltage divider breadboard.  Whoops.  The tiny breadboard with the voltage divider began to rust inside so it got really difficult to keep it working correctly.

This is for the plot named "Indoor 12V Lighting System" at https://www.SDsolarBlog.com/montage

I built a new Uno/breadboard from scratch and swapped it in with the breadboard stuck onto the plastic case.  All nice and tidy.

But the analog inputs were really strange.  It would read really close, but then minor changes to the software would produce wildly varying results.

Imagine my surprise when this morning I discovered that I had plugged the divider's analog input to A4 instead of to A1 where it belonged.

Now that it has been fixed all is well.  As long as the correct pin is being used in the digitalRead it seems not to matter, perhaps.

Here is the plot from before then after I moved the input to the correct location:

The actual voltage was falling from 12.7 down to 12.5, and after moving the pin it settled down to the correct reading.  Then I turned on the charger while the sun is up.  It is tracking the voltmeters perfectly now.

Clearly, the problem was that I was reading the wrong pin.  My fault, obviously. But it got me wondering just how much they affect each other.

So my question is about why I was getting any readings at all?  I would have hoped that the analog inputs were truly separate from each other.  Instead, it appears as if there is crosstalk of some kind.

Is this a common issue?

New information

I see that it has been pointed out that this was discussed in this Q&A:

Should all unused analog input ports be tied to ground for accurate A2D measurements?

But since that does not call it an imperative, just "one of the problems with using analog" I would have assumed that this is not common, so perhaps there is an implied answer there.

It would be a project all by itself to use half the small breadboard to distribute ground to all the other analog pins.  And I've never seen this referenced in any of the documentation.  Nor is there a tag for crosstalk.

So my question still stands:  Is this common when measuring a DC voltage?


texts: How can I rewrite my Bluetooth Classic Arduino code into Bluetooth Low Energy Arduino code (and have everything working the same)

texts:
My original code for BT Classic
My Work in Progress BLE Code
I am trying to take all I did in BT Classic and have it working exacly the same in BLE but the Rssi keeps returning 0's in the BLE code and I don't get why, even after I do connect with my iPhone to the Esp32 the Rssi is still read as 0's.
In the BT Classic example everything works perfectly fine, but I am struggling to make my BLE code work.
What the first code does is reading Rssi signal from any device that connects to the Esp32, aproximating a distance based on the values and outputing the resulting Distance and Rssi in a list of pairs form via text that is sent to the other device, continously so that I can use that information to generate a graph and do various things with it.
I tried taking all I did in my BT Code and replicate it in BLE but it's not working at all, with rssi showing as 0 no matter what, and I've also read through the two Gatt Api's and tried replicating the same functions but there were some I didnt find an equivalent for in the BLE GATT Api:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/bluetooth/esp_gap_ble.html
If anyone can guide me it'd be great. To make a summary, the first 0bin link represents the BT code I need to follow and the second 0bin link represents the BLE code I need to have it working just like the BT code (have it do the same exact things).


texts: Arduino loses its program under unusual conditions

texts:
I have a pretty complicated setup: an ATMEGA328p chip (found in the Uno, Duemilanove, etc.) on a Diavolino board (from EvilMadScientist) running at 8 MHz (instead of the normal 16 MHz).  This should be basically the same thing as the 3.3V arduino pro from the code's point of view.  On top of this is a custom shield including a bunch of digital and analog devices with SPI, I2C, and serial interfaces.

This is supposed to run for days or weeks at a time.  In normal conditions--on the ground outside--it does fine.  However, in two recent tests, it lost its program and stopped working.  One of these was in a cold low-pressure chamber (-40 C/F).  The other was outside mounted on a flying quadcopter.  Reprogramming it fixed the problem; before reprogramming, neither a reset nor power-cycling would get any response from it.

Has anyone ever heard of an arduino bricking itself like that?  My best idea for how this could happen is that somehow the chip was put into a state where it treated incoming serial data as a new program to run.  Also, I'm speculating that connections between the two boards could have been disrupted by thermal contraction or vibration in those tests.

Thanks for any help!


texts: How can arduino read a frequency higher than 16Mhz?

texts:
I will like to understand how does Arduino measure a frequency. Also how does my voltmeter can measure a frequency as well. Since I am a beginner on using microcontroler I would read a frequency like this:

void loop()
{
    while(digitalRead(myPin)==HIGH)
    {
       // pin is high
    }
    // measure time using millis (this is the time the pin was high)

    while(digitalRead(myPin)==LOW)
    {
       // pin is low
    }
    // measure time using millis (this is the time the pin was low)

}

With this code it makes sense to me how to measure a frequency and a duty cycle. The problem with this code is that it will probably be very slow and I it will probably read frequencies up to 100Hz and less.

So my questions are:

How can arduino read frequencies higher than 100Hz? How does it achieve that?
I Googled arduino's frequency and it shows to be 16MHz. That means arudino can read frequencies up to 16Mhz? Ethernet cables specifically CAT5 has a frequency of 100MHz. That means that it sends signals 100,000,000 in one second! How could Arduino send that many signals in one second if I where to buy a Ethernet shield such as this one?