texts:
What I want to do is make a ATTiny IC become a slave on the 1-wire bus, with its own S/N and command list for its specific functions.

What I want to know is if I can use the one wire library from the arduino site to send data as a slave.

For example, you can have a slave in one room with multiple types of sensors which would report to the master on requested information, or the master can tell it to control something like blinds.

Question
Would I have to monitor the bus line and respond to a request from the master and also take into consideration the way a normal sensor would send data? What frequency should I run the slave at to get the best functionality?

I won't use parasitic power, as a note.


texts:
I am controlling an ADC with my Arduino Uno. I would like the clock of the ADC to be the same frequency of the Arduino.
Is there any way that I can have a constant clock output from one of the Arduino pin ?

Thanks,

Liam


texts: What is the maximum current for each I/O pin?

texts:
Question

As far as I know each I/O pin has to keep around 20mA, what are the consequences of going higher or lower? But if I am using all I/O pins is there a maximum current value I should keep in mind? For example, the sum of all currents in all pins should not be greater than 100mA.


texts: I bought a ATmega328 microcontroller and burn the bootloader. Now I want to upload code directly from pc to the microcontroller on bread board. I have max232 ic for the communication but I recently knew that I need a serial port rather usb to connect max232 to pc. There are many usb to serial converter available on the market but can I make my own? One more thing is there any other way burn program from arduino ide to microcontroller via USB on bread board without having the arduino board. Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.


texts: How to capture the compilaton output to a text file in Windows?

texts:
I am trying to capture the verbose output of the compilation to get it into a text file. I am using the IDE 1.8.12 running on Windows 10. I have tried looking for a right mouse button context menu, CTRL-C doesn't work, and finally in desperation, the CMD.exe trick of hitting the Enter key after selecting text.
I also went to the build folder in appdata/local/temp/arduino_build_nnnnn but there's nothing like that there.
There is a topic already about this but it refers to the Linux IDE which can be launched from the command line. It turns out that it's somewhat the same on Windows.


texts: How to combine Leonardo with Ultrasonic sensor?

texts:
I am working on an Arduino project that replaces the computer mouse. I want to do this in combination with an ultrasonic sensor. I found some nice examples on youtube, but they didn't post the code. And an example on this website. But I don't get it completely. I don't have much Arduino skills, but do have some. How can you attach for example echoPinScroll to a board?

I hope someone can give me advice on how to use this ultrasonic to control my mouse!

#include <Mouse.h>

int echoPinCursor=2;
int trigPinCursor=3;

int echoPinBtn=4;
int trigPinBtn=5;
int echoPinScroll=6;
int trigPinScroll=7;
int x;
int y;
long duracionCursor, distanciaCursor;
void setup() {
 Serial.begin(9600);
 pinMode(trigPinCursor, OUTPUT);
 pinMode(echoPinCursor, INPUT);
 pinMode(trigPinBtn, OUTPUT);
 pinMode(echoPinBtn, INPUT);
 pinMode(trigPinScroll, OUTPUT);
 pinMode(echoPinScroll, INPUT);

}

void loop() {

//mover el cursor
int direccionx=moverx();
int direcciony=movery();

Mouse.move(direccionx, direcciony,0);
delay(2);

}

int moverx(){
distanciaCursor=obtener_distanciaCursor();
if (distanciaCursor >= 1  || distanciaCursor <= 11){
   x--;
 }
if (distanciaCursor >= 12 || distanciaCursor <= 24){
   x++;
  }
 return x;
}

int movery(){
distanciaCursor=obtener_distanciaCursor();
if (distanciaCursor >= 25 || distanciaCursor <= 37){
   y--;
   }
if (distanciaCursor >= 38 || distanciaCursor <= 50){
   y++;
  }
return y;
}

long obtener_distanciaCursor(void)
{
digitalWrite(trigPinCursor, LOW);
delayMicroseconds(2);

digitalWrite(trigPinCursor, HIGH);
delayMicroseconds(10);

digitalWrite(trigPinCursor, LOW);
duracionCursor = pulseIn(echoPinCursor, HIGH);

distanciaCursor = duracionCursor/58.2;
return(distanciaCursor);

}


texts:
I own a couple of digital in-ear headphones that connect to my phone using USB (some micro, some type C), i.e. they have a built-in DAC and amp. Now instead of having to carry my phone along to listen to music, I'd like to build a portable music player - think of it as an iPod Shuffle minus the DAC+AMP - and I think the Arduino platform should be well-suited for a first prototype(?).

So if I understand correctly, then all I need is the following:

an Arduino board
some storage (i.e. a micro-SD card module)
a serial to USB-C module
some code that streams the files to serial

then "optionally":

a battery
some controls

Am I on the right track?
The headphones connect as USB OTG slave devices, so the Arduino will need to be the master - is that an issue? Also, is it possible to output serial data through the Arduino's own USB port? I've looked around, but my findings are somewhat inconclusive. On the other hand, this might not matter since I will need to power it somehow anyway...

As you may have guessed, this is my first Arduino project, so please be kind ^.^

Thanks!


texts: Arduino loading variables from an SD card

texts: Hello I have made a small game using and Arduino Uno and a Nokia 5110 screen. I use bitmaps to draw the images onto the screen. The problem is that bitmaps take up a lot of space and I can only use up to three bitmaps before running out of space. Is it possible to use an SD card to store the bitmaps on and have a method in the Arduino code to load a bitmap at a certain time, like when a button is pushed?


texts: How does this code move the bird sprite in this sketch?

texts:
I'm teaching this sketch in my class. I understand most of the sketch and can see the class that makes the bird move, but I still don't quite understand how the code makes the sprite "move." I can also see what generates the Pipes but I don't how the code creates them or randomizes them.

Here is the code for both:

Bird

class Chym {

private:
  int frameCount;
  int x;
  int y;
  int deltaIde;
  int delayFrame;

  int jumpCount;
  int maxJumpCount;
  int moveSpeed;

  bool _isDead;
public:
  void respawn() {
    x = 24;
    y = 20;
    deltaIde = -1;
    moveSpeed = 1;
    jumpCount = 0;
    _isDead = false;
  }

  Chym() {
    frameCount = 0;
    delayFrame = 0;
    maxJumpCount = 20;
    respawn();
  }

  void render() {
    if (frameCount < ANIM_FRAME / 2) {
      display.drawBitmap(x, y, flappybird_frame_1, 16, 12, 1);
    }
    else {
      display.drawBitmap(x, y, flappybird_frame_2, 16, 12, 1);
    }
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {
      y += deltaIde * moveSpeed;
      delayFrame = 0;
    }

    if (y > 35) {
      _isDead = true;
    }

    frameCount++;
    if (frameCount >= ANIM_FRAME) frameCount = 0;
  }

  bool isDead() {
    return _isDead;
  }

  void die() {
    _isDead = true;
  }

  void cancelJump() {
    jumpCount = 0;
    flyDown();
  }

  void flyUp() {
    if (jumpCount < maxJumpCount) {
      deltaIde = -1;
      moveSpeed = 3;
      jumpCount++;
    }
    else {
      flyDown();
    }
  }

  void flyDown() {
    deltaIde = 1;
    moveSpeed = 1;
  }

  int getX() {
    return x;
  }

  int getY() {
    return y;
  }

};

Pipe

class Bar {

private:
  int x;
  int y;
  int delayFrame;
  int moveSpeed;
public:
  Bar() {
    delayFrame = 0;
    x = 0; y = 24;
    moveSpeed = 2;
  }

  void setPos(int sx, int sy) {
    x = sx; y = sy;
  }

  void render() {
    display.drawBitmap(x, y - 30, bar_top, 8, 20, 1);
    display.drawBitmap(x, y + 10, bar_bottom, 8, 20, 1);
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {

      x -= moveSpeed;
      if (x < -10) x = 95;

      delayFrame = 0;
    }
  }

  int hitTest(int tx, int ty) {
    int hitX = ((tx >= x - 16) && (tx <= x))?1:0;
    int hitY = ((ty <= (y - 10)) || (ty + 12 >= y + 10))?1:0;
    if (hitX != 0) {
      return hitY;
    }
    return 0;
  }

};

https://www.youtube.com/watch?v=04cY78Y2d3g


texts:
I'm trying to use my Arduino and an ESP8266 to spam De-Auth "attacks". I am quoting attacks because I do not plan on using this for malicious or destructive purposes. I've heard that the ESP8266 supports monitor mode, but I haven't found any information about using it to spam De-Auth packets. I want to do something similar to the mdk3 command in Linux (mdk3  d).

If you need me to clarify anything, please just ask.

Thanks in advance!


texts:
My program only works when the following line is added:
Serial.begin(9600);

When this is disabled/removed the program no longer switches output state regular
I'm using an Arduino Mega 2560.
When the line is added:

The output is switched ON or OFF regular around every 1sec.

When the line is removed:

The output is switched after 1 sec (as expected) but then switched multiple times after around 3 sec.
I tried with another Arduino Mega 2560: This time, the output is switched after 1sec (as expected) but then switched multiple times right after (and not after around 3 sec).

What could be the problem?
My code:
byte inputPin2 = 2;
byte inputPin3 = 3;
byte outputPin = 13;
boolean outputPin_HIGH = false;
volatile short angle = -18;

void setup() {
  Serial.begin(9600);      //<----------------------
  pinMode(hallSensorPin, OUTPUT);

  pinMode(inputPin2, INPUT_PULLUP);
  pinMode(inputPin3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(inputPin2), ISR_addAngle, CHANGE);
  attachInterrupt(digitalPinToInterrupt(inputPin3), ISR_addAngle, CHANGE);
}

void ISR_addAngle() {
  angle = angle + 18;
}

void loop() {
  if (angle == 900) {
    if (outputPin_HIGH) {
      digitalWrite(outputPin, LOW);
      outputPin_HIGH = false;
    } else {
      digitalWrite(outputPin, HIGH);
      outputPin_HIGH = true;
    }
    angle = angle - 900;
  }
}


texts:
I'm new in robotics. I bought a mini robot ( Link ), which i rebuilt a little. Now it has legs and arms. This little robot has 4 little servos (Link). There are two wheels attached to two of these servos. I'd like to spin them, so the robot will "roll", but unfortinatly it is trickier than i tought. The servos can rotate in 360 degrees(i can manually turn them), no problem with that. The problem is, that no matter how i try, the servo will turn only 180 degrees. So obviously i am making something wrong. If i write myServo.write(0) the servo rotates 180 degrees, and if i write myServo.write(180), the servo rotates 180 degrees but in the other direction. How can i make it spin in only one direcvtion(360 degrees, more than 360 degrees)?

Thanks in advance!


texts: I have an Arduino Uno and A Raspberry Pi B+. I was wandering how I could use either as a Programbel HID Device (EX: https://srlabs.de/badusb/). The Reason I ask under the arduino section is I want to preferably use it. If not I can use either.


texts: What is the difference using library of SoftwareSerial.h and ESP8266WiFi.h?

texts:
What is the library I should use to upload the sensor data (ultrasonic and Infrared sensor) to the localhost server.

Because I saw some of the online resources using ESP8266WiFi.h library for the ESP01 and some of resources use the softwareserial.h library. So, what is the difference between these two libraries?


texts:
I was reading the ATMega34u2 datasheet and trying to figure out Sleep Mode. I know most people recommend using avr/sleep.h library. But I wanted to try out using the registers. I am fairly new to all this so sorry if this an easy question but I can't seem to really find anybody doing it like this.

When checking which registers to adjust it says this:

  The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmer’s purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up.

Now I understand setting the bit but what exactly is the sleep instruction? How do I call it in my arduino program?


texts:
The Problem
I've been working on a project that requires the use of a CAN Bus Shield v2 on an Arduino. For most of the time it has worked great, completely as intended. But recently, I was trying to hookup a 24V heater to a MOSFET to be controlled by the Arduino. I had hooked it up the pin 2 which later I found out was a bad idea because pin 2 is for the interrupt signal. I uploaded the code and the heater did not turn on.
A while later I tried to upload code to the Arduino and it would not upload, citing a not in sync error. So, switched the Arduino board out for another one of the same model and the code uploaded just fine. But, the CAN Shield was throwing a "CAN Bus Shield Init FAILED" error over and over again. And the INT light was staying permanently on. And the Rx light would stay on if I tried to send a message on the bus from another node.
My question is, will I have to purchase a new shield or is there a way to fix this?
What I have tried

Turning it off and on again
Using the shield on the old Arduino
Wiping the Arduino and adding the code again
Reverting to an older piece of code
Setting pin 2 HIGH (this turned off the INT light but did not fix the init problem)
Sending various messages on the CAN Bus
Flipping the OBD switch on/off
Trying different resistors

simulate this circuit – Schematic created using CircuitLab


texts: I am trying to print items in a structure on aruino and am getting this error on compliation

texts:
I am writing a code to measure some sensor values, store them in a struct and print them after a limit.
I am using Arduino 1.8.11, programming a DOIT ESP32 DEVKIT V1
Here is my code
#include <ClosedCube_HDC1080.h>
#include <Wire.h>

RTC_DATA_ATTR int logCounter = 0;

ClosedCube_HDC1080 hdc1080;
typedef struct {
  float Temp;
  float Pressure;
} Records;

#define maxLogs 5 // store these many records before reset
#define sleepTimein_second  10 // sleeptime in secs

#define sleeptime = ((sleepTimein_second*uS_TO_S_FACTOR));  //Final deepsleep time in uS

RTC_DATA_ATTR Records Logs[maxLogs];

#define I2C_SDA   19   // HDC1080 SDA PIN to ESP32
#define I2C_SCL   22   // HDC1080 SCL PIN to ESP32

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

  Wire.begin(I2C_SDA, I2C_SCL);

  hdc1080.begin(0x40);

    Serial.println("Record new values");
    Records[logCounter].Temp     = hdc1080.readTemp();       // Units °C
    Records[logCounter].Pressure = hdc1080.readHumi(); // Units %
    logCounter++;

    if (logCounter >= maxLogs) {
      for (int i = 0; i < maxLogs; i++){
        // Display records in CSV format to the serial port
        Serial.println(i+",");
        Serial.print(Records[i].Temp+",");
        Serial.print(Records[i].Pressure);
      }
      logCounter = 0;
    }
  } else {
    // check connection with HDC1080
    Serial.println("Sorry but HDC1080 did not respond !");
  }

  // Go in deep sleep
  esp_sleep_enable_timer_wakeup(sleeptime);

  esp_deep_sleep_start();
}

After compiling, I'm getting the following error
expected primary-expression before '[' token
What am I doing wrong?
Please help !!!
Thank you in advance!


texts:
I have an arduino attached with a RGB-Shield. I want to query my server for the RGB values periodically. I basically got it working using the Ethernet Shield but it takes too long to get the value (~500ms}. I really want to read the values from my server really really fast in an endless loop.

Can you give me any hints on how I can improve my code?

#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,1,151);
IPAddress ip(192, 168, 1, 177);
EthernetClient client;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Ethernet.begin(mac, ip);
  }

  delay(1000);

  if (client.connect(server, 80)) {
    client.println("GET /rgb.php HTTP/1.1");
    client.println("Host: 192.168.1.151");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();

    ... read from Server

  }

  if (!client.connected()) {
    client.stop();
    if (client.connect(server, 80)) {
      client.println("GET /rgb.php HTTP/1.1");
      client.println("Host: 192.168.1.151");
      client.println("Connection: close");
      client.println();
    }
  }
}


texts:
I am making a counting device, and I would like to be ensure that the count is not lost if the power is lost.
As I need to count to many millions I cannot use EEPROM writes as I will trash the nvm after ripping through the 100,000 max write cycles. I also need to ensure the count is accurate, so can't update 'every-so-often' either.

I want to write to EEPROM when the Arduino detects power down. I am reading on an Analogue input pin and am then planning on using a capacitor to hold the power on to complete the write. I have this set up but am having issues testing as I have found that when Ground is connected to GND pins and then when 5v is supplied to any I/O pin the device powers up. I have now tested a Nano and Uno and have found the same thing on both.

I have looked through the arduino site and tried looking for forums where this has been discussed, but to no avail.

Is this damaging to the Arduino if powered in this way? Does this pass the sanity check as a way of achieving my main objective of not loosing the count on power down?

thanks in advance :)


texts: How to connect NRF24 receiver and Micro SD Card Module to Arduino UNO

texts: I would like to know how to connect a NRF24 receiver and Micro SD card module to Arduino board. I have already connected the NRF24 module to the arduino board but now i can't connect the Micro SD card module since the ports like 13,12,11 are used by the NRF24 module. Is there a way to connect those two modules?. I'm trying to save the receiving data on the Micro SD card.


texts:
I would like to use a 555 circuit as an external watchdog for my Arduino project. The project is a cellular tracker that goes to sleep for an hour, wakes up and does some measurements, uploads them and then goes to sleep again. The 555 should take care that the active period does not take too long because the systems hangs, and in that case trigger a reset. My first thought was to power the 555 circuit with a PIN of the Arduino so that it only goes on when the system is awake and is turned off while sleeping.
But this does not work as the reset line has to stay high even while sleeping and if i turn the 555 off reset would also go low. Could a Mosfet help? Any other ideas?


texts:
I just acquired a Arduino learning kit, which includes a 20x4 LCD display. I was going to test it, so I grabbed an example "hello world" program from the Arduino docs, connected the display appropriately, and then "Voila! ... Oh, it didn't work.".

The display lights up both its backlight and characters, however not in any desirable pattern. The first and third lines are full white (display is white-on-blue), while lines 2 and 4 are full blue. See picture:

The below schematic is exactly how I've connected the display, which should be correct.

simulate this circuit – Schematic created using CircuitLab

I triple-checked all wiring for any shorts, adjusted the potentiometer to a good value and quadruple-checked the connections, and wasn't able to find any errors.

The dead-simple example program is following:

#include <LiquidCrystal.h>

// LiquidCrystal display with:
// rs on pin 12
// rw on pin 11
// enable on pin 10
// d4, d5, d6, d7 on pins 5, 4, 3, 2
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup() {
    // Print a message to the LCD.
    lcd.begin(20, 4);
    lcd.print("hello, world!");
}

void loop() {
}


texts: code for line following robot not working perfectly

texts:
I have made a line following robot using 2 IR sensor. My line following robot was working successfully with this code.

#define LS 2      // left sensor
#define RS 3      // right sensor

/*-------definning Outputs------*/
int LM1= 5;       // left motor
int LM2= 6;     // left motor
int RM1= 9;       // right motor
int RM2= 10;

void setup()
{
  pinMode(LS, INPUT);
  pinMode(RS, INPUT);
  pinMode(LM1, OUTPUT);
  pinMode(LM2, OUTPUT);
  pinMode(RM1, OUTPUT);
  pinMode(RM2, OUTPUT);
}

void loop()
{
  if(digitalRead(LS) && digitalRead(RS))     // Move Forward
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }
 else if(!(digitalRead(LS)) && digitalRead(RS))     // Turn right
  {
    digitalWrite(LM1,HIGH);
    digitalWrite(LM2, LOW);
    analogWrite(RM1,70);
    digitalWrite(RM2,LOW);
  }
  else if(digitalRead(LS) && !(digitalRead(RS)))     // turn left
  {
    analogWrite(LM1,70);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1,HIGH);
    digitalWrite(RM2,LOW);
  }else{
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1,LOW);
    digitalWrite(RM2, LOW);
  }
}

As I used only two sensor,sometimes it goes out of the line. So I have tried to make an advanced line following robot which could get back to track automatically when it goes out of the line.But the code is taking only the 1st value of tmp.(tmp=1) even when left sensor touches the line after white sensor and the robot goes out of the line.The value of tmp should be 2 when the robot goes out of the line and the left sensor touches the line after the white sensor.  Here is the code:

/*-------definning Inputs------*/
#define LS 2      // left sensor
#define RS 3      // right sensor

/*-------definning Outputs------*/
int LM1= 5;       // left motor
int LM2= 6;      // left motor
int RM1= 9;       // right motor
int RM2= 10;  //right motor
int tmp;

void setup()
{
  pinMode(LS, INPUT);
  pinMode(RS, INPUT);
  pinMode(LM1, OUTPUT);
  pinMode(LM2, OUTPUT);
  pinMode(RM1, OUTPUT);
  pinMode(RM2, OUTPUT);
}

void loop()
{
  if(digitalRead(LS) && digitalRead(RS))     // Move Forward
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }
 else if(!(digitalRead(LS)) && digitalRead(RS))     // Turn right
  {
    digitalWrite(LM1,HIGH);
    digitalWrite(LM2, LOW);
    analogWrite(RM1,70);
    digitalWrite(RM2,LOW);
    tmp=1;
  }
  else if(digitalRead(LS) && !(digitalRead(RS)))     // turn left
  {
    analogWrite(LM1,70);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1,HIGH);
    digitalWrite(RM2,LOW);
    tmp=2;
  }
  else//out of the line
  {
    if(tmp=1){
      analogWrite(LM1,70);
      digitalWrite(LM2, LOW);
      digitalWrite(RM1,LOW);
      analogWrite(RM2,70);
    }else if(tmp=2){
      digitalWrite(LM1,LOW);
      analogWrite(LM2, 70);
      analogWrite(RM1,70);
      digitalWrite(RM2,LOW);
    }
  }
}


texts: Opamp for amplifying 1V signal voltage to 2V

texts:
I'm doing my first electronics project where a signal that varies between -1 to 1 V is going into an analog pin on the Arduino. The amplified signal has to be read as fast as possible by Arduino. The source signal is at 60 Hz.

Will this LM324 be a suitable 4-channel opamp for my needs? How concerned should I be about the 2 mV input offset and 20 nA input current bias?

To make full use of the 10bit ADC, would you recommend using an opamp with gain of 2 and biasing the signal by +2.5V? If so, will it be better to create the bias using a potential divider across +5V and GND, or using a 2.5V voltage regulator?

Or would it be better to set AREF to 2V and bias the signal by +1V? In this case, will it be better to use a 2V voltage regulator, or a voltage divider across Arduino's 3V3 and GND using 20M and 33M resistors?


texts: Connecting to a WNR2000v4 Netgear Router via Serial Connection with an Arduino Uno and a sketch?

texts:
I was reading in the OpenWRT wiki that you can indeed connect to the serial TTY console of an Open WRT roouter using the serial console if you're careful aabout the voltages.  https://wiki.openwrt.org/doc/hardware/port.serial.cables#method_b_no_physical_changes_to_arduino_board

However, I don't know anything about the voltages of my particular model of OpenWRT router a Netgear WNR2000v4.  I know that it is accessible via 3 holes on the board but I know nothing of the voltages.  Does anyone know or have experince with this about what voltages / wires to use to access it via the serial console?


texts: 9 DoF Sensor Accelerometer Readings Inconsistent

texts:
I have the following sensor stick: https://www.sparkfun.com/products/10724

It has an accelerometer, gyroscope, and magnetometer.

I have connected it to an arduino and am reading the accelerometer values while the sensor is completely flat and the values jump all over the place:

ie
0
2
3
7
-5
12
35
-3
...

This is how I am reading them:

void Accel_Init()
{
  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x2D);  // Power register
  Wire.write(0x08);  // Measurement mode
  Wire.endTransmission();
  delay(5);
  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x31);  // Data format register
  Wire.write(0x08);  // Set to full resolution
  Wire.endTransmission();
  delay(5);

  // Because our main loop runs at 50Hz we adjust the output data rate to 50Hz (25Hz bandwidth)
  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x2C);  // Rate
  Wire.write(0x09);  // Set to 50Hz, normal operation
  Wire.endTransmission();
  delay(5);
}

// Reads x, y and z accelerometer registers
void Read_Accel()
{
  int i = 0;
  byte buff[6];

  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x32);  // Send address to read from
  Wire.endTransmission();

  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.requestFrom(ACCEL_ADDRESS, 6);  // Request 6 bytes
  while(Wire.available())  // ((Wire.available())&&(i<6))
  {
    buff[i] = Wire.read();  // Read one byte
    i++;
  }
  Wire.endTransmission();

  if (i == 6)  // All bytes received?
  {
    // No multiply by -1 for coordinate system transformation here, because of double negation:
    // We want the gravity vector, which is negated acceleration vector.
    accel[0] = (((int) buff[3]) << 8) | buff[2];  // X axis (internal sensor y axis)
    accel[1] = (((int) buff[1]) << 8) | buff[0];  // Y axis (internal sensor x axis)
    accel[2] = (((int) buff[5]) << 8) | buff[4];  // Z axis (internal sensor z axis)
  }
}

Am I doing something wrong that these values aren't the same?


texts: Arduino: wrong digitalRead results from a pullup pin

texts:
A button connects GND to PIN where PIN is any digital pin.
I want to catch the moment the button is pressed, so I wrote the following code:

void setup () {
    pinMode (PIN, INPUT_PULLUP);
    Serial.begin (9600);
}

void loop () {
    static bool wasDown = false;
    bool isDown = digitalRead (PIN) == LOW;
    Serial.println (isDown);
    if (isDown && !wasDown) Serial.println ("down!");
    wasDown = isDown;
}

While the button is not pressed, everything goes as expected: the output is all zeroes. But when I press it, the following pattern appears:

0
0
0
0
<Some other zeroes, about 10 total>
1
down!
<the same number of zeroes>
1
down!
0
...

Is it some schematic flaw?


texts: How do I send an IR signal from an Arduino

texts:
I want to send a generic (not Sony, etc.) remote's signal from my Arduino.  I have already used a IR decoder program to capture the timing of the signal:

int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    88, 88,
    174, 88,
    86, 86,
    88, 86,
    88, 88,
    86, 86,
    88, 174,
    86, 88,
    86, 88,
    174, 174,
    86, 88,
    86, 2252,
    88, 88,
    174, 88,
    86, 86,
    88, 88,
    86, 88,
    86, 86,
    86, 176,
    86, 88,
    86, 88,
    174, 174,
    86, 88,
    86, 0};

Now I need to send this through the IR LED.  I have never written a program that can modulate a signal at this microsecond level.  How would I do this?


texts: Can you connect an output pin from one Arduino to the input pin of another?

texts: I have a system that uses two Arduino boards.  One is used to control several different functions, and the other is dedicated to driving a 45 second countdown display (comprised of two large 7 segment displays.)  All this second Arduino needs is a single signal to tell it when to start.  I would like to simply connect an output pin (on #1) to an input pin (on #2) and and send a single pulse to get the clock started.  Fo something this simple, I wanted to avoid using I2C.  Can I do this?  If so, is there anything else I need to be aware of (like connecting ground to ground?)


texts:
NOTE: this code was working perfectly fine in another program.

I have a simple piece of code that puts the Arduino to sleep. When it is finished and intergrated into my project, it will only wake the processor up when an alarm from an external RTC triggers one of the hardware interrupts.

#include <avr/sleep.h>
#include <avr/power.h>

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

void loop(){
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);        //deep sleep mode
    Serial.println("Device is going to sleep...");
    sleep_enable();        //put device to sleep

    sleep_disable();        //Device restarts here on wake
    Serial.println("Device is awake...");
    delay(1000);        //to slow down serial output
}

In theory, the program should shut down the processor indefinitely because there is nothing available to wake it up.

However, the device continues waking itself up immediately after shutting down.

I have tried attaching the interrupts hoping it was some kind of anomalous watch-dog function. I have tried tying the interrupt pins to +5V and also (in a separate attempt) to GND. Nothing has helped.

What is causing the processor (and/or program) to constantly wake itself up?


texts:
My sensor output voltage values ranges from 0.6 V - 3 V. How can I convert this voltage values to ppm in the range 0-1000? Upon exposure to CO gas: 0 ppm = 0.6 V , 500 ppm = 1.52 V and 1000 ppm = 3.01 V. Which means that the sensor cannot detect under 214 ppm (approx). Can you please help with mapping the sensor output values as ppm in the serial monitor? thnk u

// the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      float voltage = sensorValue * (5.0 / 1023.0);

      // print out the value you read:
      Serial.println(voltage);

    }


texts:
What is the cheapest and best method to convert 12v(14)<->5V(3.3)? Need to connect Arduino to a car.

I need logical shifter not buck converter to connect Arduino to car 12v circuit. I would like to control electrical equipment of car by Arduino. For example, I want to connect input pin to heater, when heater is on from 12v circuit I get HIGH 12v signal which processes by Arduino, but like everyone knows, Arduino can handle only 5/3.3V. Then Arduino going to change state of equipment by connecting optocoupler/relay/transistor to  button(of elect. equip.) and will act like physical press.
P.P.S I know that more clever to hack and control by CAN bus. But not all eq. are connected to CAN bus and it`s a little bit risky but I'm working on it as well.
I'm looking for best low cost solution. I have found it on ebay . Will it work like I want? Offer DIY solutions as well.


texts:
Making sure not to blow anything up before testing.

I have an adafruit motor shield and an arduino Uno. The arduino uno has a power input and I was hoping to use it to power the motor shield, a nema-17 motor, and an I2C connection. Currently I'm using the power connection on the  motor shield to power the nema-17 motor and a serial connection to power the arduino.

Can I just connect a power supply to the input port on the ardiuno uno and power the motor shield and nema-17 step motor?


texts: Using XBee and OLED screens with Timer Interrupts

texts:
I have an Arduino board with a sensor, an OLED screen and an XBee module. I've setup the timer interrupts in timer1 to sample the sensor every one second.
I've done the following:

tried to update the OLED screen with the reading and it works.
tried sending the reading from inside loop over XBee and it works.
tried doing both of the above and the Arduino seems to shut down after a bit.
tried sending the reading from inside the timer interrupt handler and it doesn't work.

Are there limitations on what interrupt handlers can do that I'm not aware of? (Other than using time delays)

Source code

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

XBee xbee = XBee();
ZBRxResponse response = ZBRxResponse();
ZBTxRequest sensorml_level_0_zbTx = ZBTxRequest(addr64, sensorml_payload_level_0,sizeof(sensorml_payload_level_0));
ZBTxRequest keepalive_level_0_zbTx = ZBTxRequest(addr64, keepalive_payload_level_0,sizeof(keepalive_payload_level_0));

union u_tag {
   uint8_t b[4];
   float fval;
}
u;

void setup() {
   display.begin(SSD1306_SWITCHCAPVCC);
   Serial.begin(9600);
   xbee.setSerial(Serial);
   noInterrupts();
   TCCR1A = 0;
   TCCR1B = 0;
   TCNT1  = 0;
   OCR1A = 62500;
   TCCR1B |= (1 << WGM12);
   TCCR1B |= (1 << CS12);
   TCCR1B |= (1 << CS10);
   TIMSK1 |= (1 << OCIE1A);
   interrupts();
}

ISR(TIMER1_COMPA_vect){
   reading =  analogRead(SENSORPIN);
   reading = (1023 / reading)  - 1;
   reading = SERIESRESISTOR / reading;
   reading = -0.15784 * reading + 305.17;
   sendObservation(reading,00);
}

void sendObservation(float value, int id){
   char idBuffer[] = "00";
   sprintf(idBuffer,"%02d",id);
   uint8_t frame[] = {'0','1','|','0','0','#','0','0','0','0'};
   frame[3] = idBuffer[0];
   frame[4] = idBuffer[1];
   u.fval = value;
   for (int i=6;i<10;i++){
      frame[i]=u.b[i-6];
   }
   ZBTxRequest request = ZBTxRequest(addr64, frame, sizeof(frame));
   xbee.send(request);
}

I skipped most variable declarations to keep the code short.


texts: How do I send a string from an Arduino Slave using SPI?

texts:
I have an Arduino Uno acting as a master with 3 Arduino Nano's acting as a slaves.

Looking at this example:
http://www.gammon.com.au/forum/?id=10892, it tells me how to send a string from the master to the slave, but I didn't see any examples sending a string from the slave to the master device. I was able to successfully send and receive digits to/from the master and slave, but I couldn't figure out how to send strings from the slave to the master based on the example.

My understanding is that SPI communications can only send information byte by byte, so am I supposed to convert my string into a byte format before putting that into the SPDR variable so that it can be sent back to the master?

In any case, would I be able to get some pointers on how to send strings from the slave to the master?

Thanks in advance.


texts: Getting "Undefined reference to vtable for {classname}

texts:
I have a large collection of libraries that compile correctly but won't link. I am using Visual Micro for Visual Studio 2015. Here is the complete collection of error messages:

CommandPattern3.cpp.o:In function `DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
CommandPattern3.cpp.o:In function `__static_initialization_and_destruction_0
CommandPattern3.ino:undefined reference to `DualMotorRomeo  ~DualMotorRomeo()
collect2.exe*:error: ld returned 1 exit status

Error compiling for board Arduino/Genuino Mega w/ ATmega2560 (Mega 2560)

I have been through the code with a fine toothed comb, but cannot see what references are undefined.

Is there some Windows 10 utility that can examine the vTables and help me find what is missing?

The code base is too large to post, but I can provide a ZIP file with all the code in it for anyone willing to help.


texts:
I am new with Arduino and I made something very basic and I don't know why it is not working . I placed the positive led in pin 13 and the negative in GND and wrote this code :

#define LED 13
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

I verified if it 's connected to Arduino Uno and when I upload the code I have this errors :

Sketch uses 924 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't set com-state for "\\.\COM4"
An error occurred while uploading the sketch

Sometimes IDE has problems ? What I did wrong ?


texts:
I am following this tutorial to learn about Arduino wireless communication. I have 2 Arduino unos with Xbee S1s sitting on Xbee Pro shields.

I've programmed the Xbee S1s by screening into the /dev/tty/* and configuring them with: +++, ATID1234, ATMY1000 (ATMY1001), ATDL1001 (ATDL1000) and ATWR. I've double checked the values to ensure they are correct.

So i've created a super simple Sender and Receiver package:

Sender.ino

int counter = 0;

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

void loop() {
  Serial.println(counter++);
  delay(1000);
}

Receiver.ino:

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

void loop() {
  Serial.println("Looping");
  while (Serial.available() == 0);    // wait
  int counter = Serial.parseInt();
  Serial.println(counter);
  Serial.flush();
  delay(500);
}

So first of all, when I upload my program to my arduino, I make sure that the S1s are not attached to the Pro shields which is attached to the unos.

When both of my unos are powered, I see a red light blinking but no indication of "busy blinking" which is supposed to happen when two XBee S1s are connected to the same channel. I am currently seeing a consistent blinking at about 1 second frequency.

Can someone tell me why I am only able to see "Looping" in my Serial monitor on my receiver?


texts: Remove a sudden pulse on pin d3 of nodemcu when powering it up

texts:
I am using node mcu and a 2 channel relay connected to the motor via pin d3.
When I power on the circuit, it shoots a pulse to the relay and i think it will damage the motor.
Please suggest me how to stop that pulse from turning on the motor.


texts: 2 way communication between Arduino with XBee and Computer

texts:
I have an Arduino Uno with a Wireless SD Shield and XBee S1 and a PC with another XBee S1 connected to it. What I'm after is for me to be able to send a message from my computer and receive a message back from the Arduino (For now let's just say if the Arduino receives a "1" I want it to send an "A" back)
Here is the code I have been practicing with (courtesy of SparkFun)

#include <SoftwareSerial.h>
SoftwareSerial XBee(0, 1); // RX, TX

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

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

(I have changed the pins from 2,3 to 0,1 as the latter is on the Arduino itself)
I have set my Xbees up and have been able to get them to talk to each other when both connected to separate PC's, but I am having trouble getting the Arduino to send information to the other XBee. When I try and send data from the Arduino IDE both RX and TX Led's flash.
Could anyone steer me in the right direction?


texts: Addressable RGB strip works fine individually but cannot set all LEDs to full white

texts:
I have a 5 meter strip of 12V digital RGB LEDs. The chip is WS2811 (see photo of IC). There are 50 addresses on the strip.

Using the FastLED library, I am able to run the "FirstLight" example that chases full white with a single address at a time, up and down the length. That works fine. So I know they individually perform properly.

However, if I set all LEDs to full white (255), the first few addresses look white but then the higher the address, the more red it is. See photo below. The strip starts in the center of the reel.

#include <FastLED.h>

// How many leds are in the strip?
#define NUM_LEDS 50

// Data pin that led data will be written out over
#define DATA_PIN 5

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

// This function sets up the ledsand tells the controller about them
void setup() {
    // sanity check delay - allows reprogramming if accidentally blowing power w/leds
    delay(2000);
    Serial.begin(115200);
    Serial.print("### SETUP ###");

      //Both strips are ordered BRG
      FastLED.addLeds<WS2811, DATA_PIN, BRG>(leds, NUM_LEDS);
      //FastLED.addLeds<UCS1903, DATA_PIN, BRG>(leds, NUM_LEDS);

}

void loop() {

   for (int i = 30; i < NUM_LEDS; i++) {

       leds[i] = CRGB::White;

   }

   FastLED.show();
}

To debug, I tried turning on just the last half. The result was still problematic:

for (int i = 30; i < NUM_LEDS; i++) {

    leds[i] = CRGB::White;

}

I then tried setting all LEDs to white at half brightness, and that looks much better, but the LEDs at the outside are still off-color compared the inside:

I've tried setting the whole strip to full blue, and that works fine.

I also have another nearly identical LED strip that instead uses the 1903 chip. The same code (initialized for 1903 instead of WS2811) works just fine on the 1903 strip!

Other things I've ruled out:

I'm using a bench power supply capable of 5A, this strip pulls less than 1.5A on full white.
I have verified the supply holds at 12V
I have not let the LEDs heat up while coiled in the reel. I make sure to unplug them after observing their color.

What could cause this on the WS2811 strip while the 1903 strip works perfectly?


texts:
I've connected the MCU to a cheap chinese 24/12v to 5v car phone charger and hooked some wires to a relay.When I try to program doesn't matter if the pin is set to high or low , as soon as I touch the "IN" wire from the relay into any of the selected pins, the relay auto actives.

here is the schematic
The charger input is hooked to a 12V drill battery for tests and the output to arduino is an usb port that I soldered wires to it's respective poles.

USB from Chinese charger Positive pole ------- NodeMcu Vin
USB from Chinese charger Negative pole ------- NodeMcu GND
USB from Chinese charger Positive pole ------- Relay   VCC
Relay Ground --------------------------------- NodeMcu Gnd
Relay DataPin -------------------------------- NodeMcu D0 or D1

And here's the code:

int port = D0;
int portB = D1;

void setup() {
Serial.begin(115200);
pinMode(port,OUTPUT);
pinMode(portB,OUTPUT);

digitalWrite(port,HIGH);
digitalWrite(portB,LOW);

}

void loop() {

}

But the result is that the relay will always be on activated ( IN pin = Low ) even connected to D0 that is high... Any ideas ?


texts: Can internal and external pull up/pull down resisters be used together?

texts:
What happens if a sketch uses code like pinMode(18,INPUT_PULLDOWN) to configure internal pull-down (or pull-up) resistors, but is used in a circuit where external resistors are also present?
Are there likely to be any problems, conflicts or unexpected behaviour, e.g. if software sets a pull-down, but there is an external pull-up, or visa versa?
I am using an ESP32 (which has both internal pull-ups and pull-downs available on most GPIO pins), but I would appreciate a general answer. To clarify, I am not after the pros and cons of using external resistors (which is discussed in other questions), but the potential pitfalls of using both, especially if they are pulling in opposite directions.


texts: Get USB host controller serial number or ID using Teensy or other HID devices

texts: I have a Teensy board and would like to know if there's a way to get a serial number (or any other kind of ID that is preferably unique) of the host controller that I plug my Teensy into. E.g. can I get any unique identification numbers of my Macbook's USB controller when I plug my Teensy into it? C/C++ code examples for Teensy would be highly appreciated.


texts: Servo noise during program flash on Arduino

texts:
I'm running serveral servos using a driver A4988 and external power supply. Everything works fine.
I've just noticed one issue that I can't explain.
As soon as I upload a new program version on my arduino uno, while the external power supply is one, the servo makes some strange noises. After the upload has finished, the noise disappears.
Without any further details, can you explain this behavior? Does the arduino set some Pins to HIGH during flashing?
Thanks!


texts:
I have a little problem. I have a motor driver (L298N). When I engage in electricity, my 2 motors start and after 5 second stop. Then they stop for about 2 seconds, and then start and in a moment (0.5 second) turn off. This make still around (go about 0.5 s, stop for 2 seconds...). And my motor driver is very hot after 1 minute.

Is it possible that it is because of weak voltage? (The motor driver is for 6-35 V, and I have a 6 V battery).

L298n:
enter image description here

There is my code on Arduino:

const int motorPin1  = 9;
const int motorPin2  = 10;
const int motorPin3  = 6;
const int motorPin4  = 5;

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
}

void loop() {
  forw(3000);
  back(3000);
}

int fast = 255;

void forw(int timer) {
  analogWrite(motorPin1, 0);
  analogWrite(motorPin2, fast);
  analogWrite(motorPin3, 0);
  analogWrite(motorPin4, fast);
  delay(timer);
}

void back(int timer) {
  analogWrite(motorPin1, fast);
  analogWrite(motorPin2, 0);
  analogWrite(motorPin3, fast);
  analogWrite(motorPin4, 0);
  delay(timer);
}


texts: Arduino UTFT Touch align RIGHT with margin

texts:
I am using a TFT Touch screen on an Arduino Mega, with UTFT and UTouch libraries.
When I use the code below, the text is aligning to right, all the way to the edge of the screen. Is it possible to give it a margin?

tft.print("Text", RIGHT,12)

Thank you,
Andi


texts: Distance from Arduino UNO to LCD: How far?

texts:
How far from the UNO can I place an LCD (the typical 16x2)? Assuming that everything that is plugged into the LCD comes directly from the Arduino (power and data).

I'd like to mount the LCD on the wall at eye level, my "box" will be on the floor, close to a power source.


texts:
I had assembled a board with esp8266ex bare chip with 4MB eeprom for esp and also can be shared with host MCU. I had gone through some googling and found that using eeprom function I am able to write data in eeprom using esp8266ex. But I had seen the limitation of 4KB. Then I had researched more than I found that there is a way to increase that.

So my question is, Is there are any issue if I changed that 4KB to 2 MB or more in esp8266 library?

I am using arduino IDE for Esp programming.


texts:
My serial monitor window opens frozen, without any output or possibility to input, or even activate the window.
Sketch is very simple, but behavior is same even with empty sketch, so I assume problem is not in sketch. I also checked if sketch is uploaded correctly by uploading simple sketch with blinking diode, which worked.
Same behavior with Arduino Nano and Uno.
I tried to reinstall IDE, uninstalled, removed and reinstalled serial driver (ch340) with no success.
I can see Serial monitor window only on windows taskbar, it won't activate after click.
Until now I haven't had any significant problems with IDE or serial monitor for years.


texts:
Part of my project is to build heart rate monitor from Nano and a PulseSensor. I am having trouble working with the Fast Fourier Transform part of the code.

This code here is from a library (arduinofft) that can be found in the arduino IDE. When testing the arduino the serial printer returns values of about 51 bpm, which is far to low, compared to other devices of about 70bpm.

What i have done:

edited the library to only take the last 25 to 128 samples (only when computing the max peak), to off-set the DC. Previously getting readings of 5 BPM
changed the sampling frequency to 5.6Hz to get the range of 0 to 2.8Hz range for the hate rate

What i don't understand:

the sampling period, if the samples are taken and put into an array every second what does the period do.
Also if samples are taken every second is this enough to get a good reading on a heart rate shouldn't the sample be maybe of 15-30 seconds?
If this is so, should i put another array at the bottom. To capture the results every second upto 15 or 30, print the average then first in first out  the array of new values?

#include "arduinoFFT.h"

arduinoFFT FFT = arduinoFFT(); /* Create FFT object */

#define CHANNEL A0
const uint16_t samples = 128; //This value MUST ALWAYS be a power of 2
const double samplingFrequency = 5.6; //Hz, must be less than 10000 due to ADC

unsigned int sampling_period_us;
unsigned long microseconds;

double vReal[samples];
double vImag[samples];

#define SCL_INDEX 0x00
#define SCL_TIME 0x01
#define SCL_FREQUENCY 0x02
#define SCL_PLOT 0x03

void setup()
{
  sampling_period_us = round(1000000*(1/samplingFrequency));
  Serial.begin(115200);
  Serial.println("Ready");
}

void loop()
{
  /*SAMPLING*/
  for(int i=0; i<samples; i++)
  {
      microseconds = micros();    //Overflows after around 70 minutes!
      vReal[i] = analogRead(CHANNEL);
      vImag[i] = 0;
      while(micros() < (microseconds + sampling_period_us)){
        }
  }

  FFT.Windowing(vReal, samples, FFT_WIN_TYP_RECTANGLE, FFT_FORWARD);    /* Weigh data */
  FFT.Compute(vReal, vImag, samples, FFT_FORWARD); /* Compute FFT */
  FFT.ComplexToMagnitude(vReal, vImag, samples); /* Compute magnitudes */
  double x = FFT.MajorPeak(vReal, samples, samplingFrequency); /* Compute largest peak*/
  double y = round((60/(1/x)));
  Serial.println(y);  //print bpm
  delay(2000); /* Repeat after delay */
}

Thanks for any help


texts: How to properly reverse DC motor direction with 2 limit switchws

texts:
Hello i am trying to reverse a dc motor direction upon hitting either limit switch. but noting is working can some one point me in right direction. all example i find use stepper motors and step count.

const int sw2 = 2;          //Up Limit switch
const int sw3 = 3;          //Down Limit switch
const int ic1_2 = 8;        //TA8409S IN2
const int ic1_1 = 9;        //TA8409S IN1
const int enable = 10;      //TA8409S Enable (motor)
int sw2State = 0;
int sw3State = 0;

void setup() {
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(ic1_1, OUTPUT);
  pinMode(ic1_2, OUTPUT);
  pinMode(enable, OUTPUT);
  digitalWrite(enable, 1);
  Serial.begin(9600);
}

void loop() {
  tilt_up();
}

void tilt_up()
{
Serial.print("up Started\n");
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, HIGH);
  sw2State = digitalRead(sw2);
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
    Serial.print("sw2 pressde\n");
  }
}

void tilt_down()
{
  Serial.print("down Started\n");
  digitalWrite(ic1_1, HIGH);
  digitalWrite(ic1_2, LOW);
  sw3State = digitalRead(sw3);
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
    Serial.print("sw3 Pressed\n");
  }
 }


texts: Write a condition to execute 2 switch-case functions?

texts:
I'm new to programming and using Arduino products, and was wondering if someone wouldn't mind assisting me with a project I'm trying to tackle?

If you review my code below, I have 3 conditions within my "idle" case, and the program is constantly looking for any of those 3 conditions. If the first condition is met, then case 1 is called; if the second condition is met, then case 2 is called; if the third condition is met, then case 3 is called. All 3 cases return to the "idle" case once done running.

What I would like to do is find some way to insert the "warning" case if any of the conditions are met, BEFORE going to case 1, case 2 or case 3, without writing the functions of the "warning" case over each time for each of the other 3 cases. Essentially, the flow would be like this:

condition 1 --> warning --> case 1 --> case idle;

condition 2 --> warning --> case 2 --> case idle;

condition 3 --> warning --> case 3 --> case idle:

void loop() {
  static byte theState = idle;
  switch (theState)
  {
    case idle:
      if (voltageA0 > 1.0) {
        theState = case1;
      }

      if (voltageA1 < 2.0) {
        theState = case2;
      }

      if (voltageA2 > 3.5) {
        theState = case3;
      }
      break;
    case warning:
      digitalWrite(7, HIGH);
      delay(5000);
      digitalWrite(7, LOW);
      delay(0);
      break;
    case 1:
      digitalWrite(8, HIGH);
      delay(2000);
      digitalWrite(8, LOW);
      delay(0);
      theState = idle;
      break;
    case 2:
      digitalWrite(9, HIGH);
      delay(2000);
      digitalWrite(9, LOW);
      delay(0);
      theState = idle;
      break;
    case 3:
      digitalWrite(10, HIGH);
      delay(2000);
      digitalWrite(10, LOW);
      delay(0);
      theState = idle;
      break;
  }
}

Also, if there is a more efficient way to do this, code-wise, I'm all ears!


texts: Is there a library to use MQTT with a bluetooth module (HC-06) instead of WiFi? If not is there a similar ready for use implementation of a publisher subscriber pattern available?


texts:
So, I have 3 buttons to a arduino.
I want to detect the button press on the 3 of them.

For that, i've created a function:

int OnKeyPress (int port) {

  int  LastState, BeginState, r;
  r = 0;

  BeginState = digitalRead(port);

  if (BeginState != LastState) {
      if (BeginState == 1) r = 1 ;
  }

  delay(5);
  LastState = BeginState;
  return r;
}

I want to instantiate 3 instances of this code, separately and they have to retain this variables int  LastState, BeginState, r; for each button, and the next time the function runs on the loop, the variables are the same of when they ran last time.

Just, how?


texts:
I have to control with an Arduino UNO and xbee shield:

9 5V relay
9 RGB LED

What kind of multiplexing can you advice me? Do I have to use external power supply (like 12V DC external from arduino or from vcc)? Is there any kind of already ready-to-use shield?
EDIT
I'm planning to use a 8 relays shield plus one single relay


texts: Powering 30+ LEDs and flickering one at random

texts:
I'd like to power 30+ LEDs, while having a single LED (at random) flicker every 10-15 seconds.

Is this possible to do using an Arduino? I totally new to this so please bear with me.

This is the type of flicker effect I'm hoping to achieve: https://www.youtube.com/watch?v=753-lkao8l0

Many thanks


texts: Need help with understanding the CapacitiveSensor circuit diagram

texts:
Hey guys I need help with understanding the circuit diagram from this link: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense

As of now, this is the schematic I drew from what I understand:

I know it is wrong since they make use of 2 capacitors, but I do not know where should the other capacitor be connected to.


texts:
I modified the SD sketch for ESP8266 to read WIFI setting from a file named CONFIG.TXT. The text file's content format is SETTING=VALUE. Ex.

SSID=AP001
KEY=AP001

I manage to separate the SETTING and VALUE
My code:

#include <SPI.h>
#include <SD.h>

File myFile;

void readWifiConfig() {
  Serial.println("Initializing SD card...");
  char temp;
  bool isSetting = true;
  if (!SD.begin(4)) {
    Serial.println("Initialization failed!");
    return;
  }
  Serial.println("Initialization done.");
  myFile = SD.open("CONFIG.TXT");
  if (myFile) {
    Serial.println("CONFIG.TXT");
    while (myFile.available()) {
      temp = myFile.read();
      if (isSetting == true) {
        if (temp == '=') {
          Serial.print("="); //Writes '=' to console
          isSetting  = false;
        }
        else {
          Serial.print(temp); //Writes SETTING part to console
        }
      }
      else {
        if (temp == '\n' || temp == '\r') {
          isSetting = true;
          }
        else {
          Serial.print(temp); //Writes VALUE part to console
          }
        }
    }
    myFile.close();
  } else {
    Serial.println("Can't open CONFIG.TXT");
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);
  readWifiConfig();
}

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

}

Output:

Initializing SD card...
Initialization done.
CONFIG.TXT
SSID=AP001
KEY=AP001

I want to write the values to their corresponding variables and I don't know how.

char* ssid;
char* key;


texts: ATmega 8 wrong timing with Arduino NG bootloader

texts:
I have build simple Arduino ISP programmer, which works fine on ATmega 328 chips (when I select Arduino UNO board) and a ton of others (tiny45, tiny2313). But, when I want to program an ATmega8 chip, it writes it succesfuly, but then the chip runs at 1/16 of the desired speed! (for example a delay(1000) in code takes 16 seconds real-life). I have a 16 MHz crystal oscillator with capacitors connected to the chip, so I thought that the problem is not there but... when I remove the crystal, the chip still runs the same, it still takes 16 seconds.
So I assume two possibilities:

the crystal is somehow broken, so the chip runs from some internal
thing? But I tried multiple crystals, all the same,

OR

I am doing something wrong, but I really don't know what...

Does somebody have an idea what may be wrong or how to test it? Or feel free for more details...Thanks

EDIT: In IDE, I am selecting "Arduino NG or older" and then I select ATmega8  as processor. I am uploading the sketches directly, without bootloader.


texts: Keyboard.println missing characters when I print long strings

texts:
The topic is pretty straight forward: When I use Keyboard.println(), it sends short (up to 30-ish) strings just fine, but when I get up around 100 characters there are random characters missing. "Random" - meaning it is not all the time, it's somewhat consistently the same characters missing though.

I've checked and the data is arriving at the Arduino correctly (over web service), but once it shows back up in the notepad, it's missing random stuff.

Any thoughts or suggestions?

Edit: Examples as requested:
I'm sending...

  cheat SpawnDino Blueprint'/Game/PrimalEarth/Dinos/Pelagornis/PelaCharacter_BP.Pela_Character_BP' 10 1 1 10

And what's printing is...

  cheat SpawnDino Blueprint'/Game/PRIMALEarth/Dinos/Pelgornis/PelaCharacter_BP.Pela_Character_bP' 10 1 1 10

I've actually noticed now that it's changing capitalization too, the BP to bP and Primal to PRIMAL.


texts:
So I have two Arduinos (Arduino Nano) and I'm trying to get them to communicate via SoftwareSerial.  I have the 'sending' Arduino's D10 pin connected to the 'recieving' Arduino's D11 pin, and vice versa.  On my sending Arduino, I have the following code:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

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

void loop() {
  if (mySerial.isListening()){
    digitalWrite(2, HIGH);
  }
  mySerial.write(5);
}

and on my receiving Arduino, I have:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(11, 10);

void setup() {
  pinMode(2, OUTPUT);

  Serial.begin(9600);

  mySerial.begin(9600);
}

void loop() {
  mySerial.listen();
  if (mySerial.available()>0) {
    digitalWrite(2, HIGH);
    char inByte = mySerial.read();
    Serial.write(inByte);
  }
  digitalWrite(2, LOW);
}

(with D2 being hooked up to an LED for both).

I can't get it to read anything.  Nothing seems to be available for the receiving Arduino (the LED is off).  What am I doing wrong?


texts: LCD not displaying any character with I2C or when used separately

texts:
I have an arduino uno and pin connection for I2C are -

SDA --> A4
SCL --> A5
VCC --> 5v
GND --> GND

This the code i am uploading taken from the examples -

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

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup()
{
    // initialize the LCD
    lcd.begin();

    // Turn on the blacklight and print a message.
    lcd.backlight();
    lcd.print("Hello, world!");
}

void loop()
{
    // Do nothing here...
}

The LCD shows nothing after upload . I have tried adjusting the potentiometer on I2C; just the blank characters come up.


texts:
Is the a way to check the status of a bit in an arduino Uno?

Like how in Atmel AVR, there is bit_is_clear or bit_is_set


texts:
I read exist articles about it, but still not understand how to do that.
I have a Genuino 101 and an EEG Headband (neuro interface). Need to get data from neuro device. With external HC-05 bluetooth module the code look like this:

 SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
 bluetooth.begin(57600);
 while (!bluetooth.available()) {}
 byteRead = bluetooth.read();

Has anyone encountered a similar problem?
Thanks!


texts: Beginner Arduino Project: Drumming Robot

texts:
So, I've got a music degree, 5 years programming with Ruby and 7 with Pure Data. I've also got hold of an Arduino and a Raspberry Pi.

Anyway, I've seen a number of Arduino projects which involve firing events which cause a stick to hit a drum, but I really don't know where to start.

I have a wicker penguin that I want to have play the drums:

What components do I need to produce this kind of one-off percussive event?
Can I trigger these events from Ruby?


texts:
Is it possible to connect these two shields to my Arduino Uno? After a research on the internet, I discovered that they use some of the same pins. Even so, is it still possible for me to connect the LcdKeypad and the ArduinoWifi on my Arduino Uno? (the LCD would be on top)

Here are the pic of the shields, and some information:

LDC KEYPAD

Arduino WIFI

WiFi shield info:

  The Arduino communicates with the processor WiFi shield with the microSD card by SPI
  (Eurotherm the ICSP bus) that is on pins 11, 12
  and 13 at Uno. The pin 10 is used to select the HDG104 and pin 4 to
  the microSD card(i dont need the pin 4 cause i wont use SD). These pins can not be used
  for input and output. The
  digital pin 7 is used for initialization of the communication protocol
  between the shield and Arduino WiFi and should not be used.

LCD info:

  This shield we will have to use the following sequence to initialize
  the library LiquidCrystal:
  LiquidCrystal lcd (8,9,4,5,6,7);

As you guys have noticed, there is the pin 7 on both shields that I need to use. How would it work? Can I do this? If i can't, is there any solution that I can expand my pins that would not result buying a Mega?

I still have to connect two INFRA-RED sensors and a motor (using pins 0, 1, and 2). I don't know if i can connect on the pins TX and RX (they seem to work).


texts:
I made a simple temperature controller on DHT11.
I want it to work with DHT22 as well having the same code.

However, I can’t find a way how to get known what type of sensor is installed.
Is there a way?


texts:
I have connected an arduino serial port to my PC and monitoring the output in realterm. I am trying to print:
CR
11.98,123,3520,01CRLF

But it is resulting with some delay. First
CR
1
Is printed. After sometime, say 0.25sec, the rest of the data (1.98,123,3520,01CRLF) is received. Finally its shown like
CR
11.98,123,3520,01CRLF

Why is there a delay between CR1 and the rest of the characters when printing using a single serial print!?

Serial.print("\r11.98," +string1+","+string2+",01"\r\n);

string1 & string2 hold data values from 2 separate sensors.


texts:
So, i've worked with the pySerial module for python, where I communicated with my arduino via serial. However, this module only works for 32bits and I would like to make my project work on both architectures (I know the person could just install the 32-bits version on the 64-bits architecture). Also, the connection fails a lot of times and I wasn't able to correct it.
I think I can use the true USB power of the arduino Leonardo to connect to the python in a different way, but I don't know where to start. But I think this approach will be more professional.
Im really intersted in learning, so if you guys could at least indicate documents so I can understand how to make this connection between Leonardo and Python, I'll be happy. I've read the arduino page about the CDC but couldn't find useful information.

Thank you so much.

Update:

When i used serial, I had problems with messages getting acumulated at the buffer, and then after some seconds i was reading 10s delayed messages. Also, when I sent a string like: "12345678", it was really easy to get one number less, like: "1345678". This happened frequently to me. So I think I need to implement a protocol to deal with these problems.


texts: I am trying to build a fan controller for my pc, the problem is that the example code(http://playground.arduino.cc/Main/ReadingRPM) im using utilizes interrupts. On my uno I can then only read the rpm of one fan. I want to also control the rpm (via pwm) and monitor temperatures (via thermistors) Anyone know how I coud do it differently? I. E. Without interrupts. I would also like it to be as close to real time as possible


texts: Arduino pro mini (clone) @1Mhz target does not answer

texts:
Recently I have been experimenting with battery powered sensor (mySensors).

I created node with 3.3V Arduino Pro Mini (ATMega328P @ 8Mhz with nordic radio chip and BME280 sensor) and successfully programed it many times using either USBAsp programmer or serial (to USB) programmer.

I wanted to lower power consumption and so I disconnected power led and burned fuses as follows:
lfuse 62
hfuse DA
efuse 7

It worked successfully and I recompiled the sketch and upload it with USBasp.
I got an error that data cant be verified. It was late in the night so I jumped to Internet and googled it. In one forum I found, post (which I am unable to find again) that stated the he was able to upload sketch when he switched programmer to 5V. (Power was connected to Vcc)

I did that and it worked fine.

Than I tried to make change to sketch and upload it again (on 3,3V) and again got verification error so I unplugged programmer and switched back to 5V.

When I did that, the device stopped answering.

I regularly used this command to check that device responds and see fuses

avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -cusbasp -Pusb

What i did

Checked wiring.
Tried program fuses on blank new arduino - worked (programmer is
fine)
Measured voltage ok
Measured current (its around 4mA, I see it as the board is not
sleeping and is actively doing something)
I noticed that when I issue command mentioned above the on board led
quickly lights up and then goes off again.
I tried to power it from raw, from Vcc and from Vcc on serial hader (picture).
I measured power on Vcc when connected to Raw pin and it reads 3.3V
so power regulator should be ok.
I used -B10 switch to averdude with no luck

My question is

Is it possible that I burned the ATMega chip?
Is it possible that I see target not answering because of USBAsp is unable to lower programming frequency? (warning: cannot set sck period. please check for usbasp firmware update.)

Please suggest if there is anything I can try before throwing it out.

Thank you.

EDIT 2017-01-07
I was able to brick another board.
I think that the programmer is the cause.

I tried to upload bootloader with fuses from arduino and it failed with verification error.

I was able to burn bootloader from command line after seting fuses and restarting the board.

When I tried to upload the program it I got

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x00 != 0x0c
avrdude: verification error; content mismatch

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: lfuse changed! Was 62, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: hfuse changed! Was da, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: efuse changed! Was 7, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: Fuses OK (H:07, E:DA, L:62)

I answered yes because in in earlier attempts it just froze.

Now the board is in same condition as the first one.

Is it possible to revive it?
Thanks.


texts: Using Arduino wireless SD Shield to save data to sd card and send to PC over wireless network

texts:
I'm using an Arduino Mega to monitor the current & voltage input to four different sensors. This works fine - the sensors work as expected and I can view the results via the Serial Monitor or Parallax DAQ for Excel.

SETUP

I also have an Arduino wireless SD shield (now retired) with an XBee module (shown in the below image):

Arduino Shield page
XBee module page

I would like to do the following:

Save the current/voltage sensors' output locally to the SD card
Send the data over a wifi connection for plotting using plotly API (see example  here)

I've seen a bunch of tutorials on how to get the shield to work but can't seem to figure it out:

Arduino WiFi shield example
Instructables
Can I connect to WiFi with an Arduino, "wireless SD shield" and XBee

Here's my code (removed the current/voltage sensor code for brevity):

#include <SPI.h>
#include <WiFi.h>
#include <SD.h>

void setup() {
  // initialize serial and wait for the port to open:
  Serial.begin(9600);
  while(!Serial) ;

  SPI.begin();

  Serial.println("Checking WiFi status:");
  Serial.print("\tWiFi Status: ");
  Serial.println(WiFi.status());

  if(WiFi.status() == WL_NO_SHIELD){
    Serial.println("\tNo Shield present.\n");
  }else{
    Serial.println("\tShield found.\n");
  }

  Serial.println("Initializing SD card:");
  if (!SD.begin(53)) {
    Serial.println("\tSD card initialization failed.\n");
    return;
  }else{
    Serial.println("\tSD card initialization successful.\n");
  }

  // attempt to connect using WEP encryption:
  Serial.println("Initializing Wifi:");
  printMacAddress();

  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void loop() {
  delay(5000);
  // scan for existing networks:
  Serial.println("Scanning available networks:");
  listNetworks();
}

void printMacAddress() {
  // the MAC address of your Wifi shield
  byte mac[6];

  // print your MAC address:
  WiFi.macAddress(mac);
  Serial.print("\tMAC: ");

  for(int i = 0; i < 5; i++){
    Serial.print(mac[5-i],HEX);
    if(i != 5){
      Serial.print(":");
    }
  }
  Serial.println(" ");
}

void listNetworks() {
  // scan for nearby networks:
  Serial.println("** Scan Networks **");
  byte numSsid = WiFi.scanNetworks();

  // print the list of networks seen:
  Serial.print("number of available networks:");
  Serial.println(numSsid);

  // print the network number and name for each network found:
  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
    Serial.print(thisNet);
    Serial.print(") ");
    Serial.print(WiFi.SSID(thisNet));
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    Serial.print("\tEncryption: ");
    Serial.println(WiFi.encryptionType(thisNet));
  }
}

OUTPUT

Checking WiFi status:
    WiFi Status: 255
    No Shield present.

Initializing SD card:
    SD card initialization successful.

Initializing Wifi:
    MAC: 0:0:0:0:0:
Scanning available networks...
** Scan Networks **
number of available networks:0

Not sure what is going on here.


texts:
I am trying to connect the wireless module nrf24l01 with the gyro mpu-6050.  Each works perfectly on its own.  However, when connecting both to a single atmega328 (in order to send over wireless the gyro data), the code runs for between 30 seconds and 5 minutes.

I have seen many people have issues, none of the suggestions have worked, but it seems like it is more about the combination than the mpu itself.  I have not had any errors, in that all the attempts have uploaded fine.

Some things I have tried (If you have experience with this device, im sure you will know what i am referring to ):
Changing clock rates from 24 to 12, and 400 to 200
Changing the header file for mpu from 100 hz to 20 hz and back
Adding pullup and pulldown resistors on sla/sda
Using external variable power supply to make sure exact voltage
Powering devices off arduino 3.3 and external 3.3
Running code without using serial reader on computer and just transmitting data

Edit:

After more debugging, I reduced the issue (I think).  As each module works fine independently, i thought there could be a code issue.  It seems though, that the issue is the combination of buffers.  I don't think this is exactly right, but to us it seems like the gyro needs to run quickly to stop the risk of causing the arduino to hang(even though we clear the buffer).

The second part is the wireless.  It seems like the code is looking by default for an acknowledgment the package is received.  This slows down the broadcasting.  So, if we disable the ack requirement, the gyro becomes stable.  However, the receiver stops receiving any packets at all.  If someone knows why, please explain.

So what we thought would work is by sending only some packets as the write with ack on a particular pipe.  This way, the gyro will be able to run stably, and the data can sometimes be sent and we can see if this is really the problem.  Again, this does not get recognized by the receiver at all.

Questions:
Does it make sense that the buffers are working against eachother, and this is not solvable through hardware.
Is there a clear reason why the receiver can not find packets that are being sent, just without the ack requirement?


texts: I am developing a 247 monitoring system with Arduino. The values need to be sent to server periodically as well as upon interrupt (Watchdog). To access the internet, I am using the SIM800 module. Now, Is it possible to HTTP inside an ISR? As far as I know, Serial communication should not be used in ISR. Then how can I communicate with SIM800? Any suggestion will be valuable.


texts: Best buffering practice for continuous SD card writing

texts:
In a simplified example, I have a microcontroller functioning as a data acquisition device - sensor data is received over UART, and then saved to an SD card.
This received data is in the form of a 12 byte struct, received at 1kHz. The microcontroller receiving the data is an esp32, with an SD card connected over spi. Not an uncommon issue, but if a typical SD card write is triggered everytime new data is received, it will take longer than the gap between samples to  write the data.
What is typically considered the best practice for this type of system, presuming the data will always be received faster than it can be written. I have seen examples of circular buffers, but presumably these will eventually fill completely and samples will be missed.
In my particular example, I have the bonus second cpu core in the esp32. Therefore, my thinking is to use 2 alternating buffers. Data will be received on core 1, and placed into the active buffer. When the buffer is full, incoming data will be written to the second buffer, and the first will be written to the SD card by core 2.
Is this a sensible solution to the problem? I am hesitant to implement anything that simply relies on an improvement in SD write speed, as I will likely need to increase the size of the data payload in the future and don't want to run into this issue again later on.


texts: Need help with my code for my project using an Arduino Uno and Processing

texts:
I am using an Arduino Uno for my project. I use 4 digital inputs and they will be triggered by 4 different relays. I would like to save the data in a *.csv file in the format below.

For example, if any of the inputs goes high, it will save a station ID, date, time it goes ON (starts). But once the input goes low, it will save the time it goes OFF (stops) on the same line.

Kindly help to advise if my code is correct because I get too many errors when I run it.

Example table in .csv file:

Date        Oven Station    Time Start     Time Stop
3/7/2017       Oven_P1_1       11:58       16:00
3/7/2017       Oven_P1_2        7:30       11:00
3/7/2017       Oven_P5_1       14:10       20:00
4/7/2017       Oven_P5_2        01:20      7:30
4/7/2017       Oven_P5_1        2:40       8:45
4/7/2017       Oven_P1_2        08:05      12:00
4/7/2017       Oven_P1_1        09:12      13:10

import processing.serial.*;

int Oven_P1_1 = 8;
int Oven_P1_2 = 9;
int Oven_P5_1 = 10;
int Oven_P5_2 = 11;
float Ovenvals [] = {0,0,0,0};

Serial myPort;
String val;
Table table;

String filename;

void setup() {
  String portName = Serial.list()[5];
  myPort = new Serial(this, portName, 9600);
  table = new Table();
  table.addColumn("id");
  table.addColumn("year");
  table.addColumn("month");
  table.addColumn("day");
  table.addColumn("hour");
  table.addColumn("minute");
  table.addColumn("second");
  table.addColumn("Oven_P1_1");
  table.addColumn("Oven_P1_2");
  table.addColumn("Oven_P5_1");
  table.addColumn("Oven_P5_2");
}

void serialEvent(Serial myPort) {
  val = myPort.readStringUntil('\n');
  if (val != null) {
    val = trim(val);
    println(val);
    float Ovenvals[] =float(split(val, ','));
    TableRow newRow = table.addRow();
    newRow.setInt("id", table.lastRowIndex());
    newRow.setInt("year", year());
    newRow.setInt("month", month());
    newRow.setInt("day", day());
    newRow.setInt("hour", hour());
    newRow.setInt("minute", minute());
    newRow.setInt("second", second());
    newRow.setInt("Oven_P1_1", ovenVals[0]);
    newRow.setInt("Oven_P1_2", ovenVals[1]);
    newRow.setInt("Oven_P5_1", ovenVals[2]);
    newRow.setInt("Oven_P5_2", ovenVals[3]);
    {
      saveTable(table, "data/OvenStatus.csv");
    }
  }
}

void draw() {
  OvenVal[0] = digitalRead(Oven_P1_1);
  OvenVal[1] = digitalRead(Oven_P1_2);
  OvenVal[3] = digitalRead(Oven_P5_1);
  OvenVal[4] = digitalRead(Oven_P5_2);
  Serial.print(OvenVal[0]);
  Serial.print(",");
  Serial.print(OvenVal[1]);
  Serial.print(",");
  Serial.print(OvenVal[2]);
  Serial.print(",");
  Serial.print(OvenVal[3]);
  Serial.print(",");
  delay(100);
}


texts: Do I need the Ground and 5 V pin connect to Led?

texts: I am building an ambilight. So I bought a 3 pin LED Strip which I power with the USB hub from my TV. Next step is to connect it to the Arduino Nano. Is it OK when I only use the dataport from the Aduino and the power only from the television?


texts: DigitalWrite Cannot Power HC-06 Bluetooth

texts:
To save power consumption, I tried to connect the HC-06 bluetooth module to a digital pin of my Arduino Nano. (HC-06 +5V <=> pin 11, HC-06 gnd <=> gnd) In that way, I can toggle the bluetooth when I am not using it. However, when I tried to pinMode(11, OUTPUT) and digitalWrite(11, HIGH), the led on HC-06 does not turn on which means it is not powered. I have tried to connect the HC-06 +5V to the 5V output of arduino and the HC-06 can turn on sucessfully. I have also tried to use a multimeter and the digital pin outputs a voltage of 5V. As the digital pins of Arduino can give 40mA while the HC-06 draws 30mA - 40mA, it should have enough power. I have also tried to use other digital pins as well but still the HC-06 cannot be powered.
What have I done wrong?


texts: I need to know how to obtain the UUID from an Arduino Nano ATmega328 for a project.


texts:
I'm working on UART communication between an ESP32 (sender) and ESP8266 NodeMCU board(receiver).

The host is sending out the following character string:

Serial.println("2753192144$1&");

The 2753192144 is the payload. The $1& is the trailer of the packet - $1 signifies a particular option for the receiver and & is the termination character to signify that the packet is complete.

On the receiver end - this is what I have:

#define MAX_REC_STR_SIZE 10
#define REC_TRAILER_SIZE 4 // $1& and string terminator
#define TRUE_TRAILER_SIZE 2 // option size really

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

void loop() {
    if(Serial.available()){
    char data [MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1];
    Serial.readBytesUntil('&', data, MAX_REC_STR_SIZE + REC_TRAILER_SIZE); // data does not contain termination &
    data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator

    // Tokenizing
    char *payload = strtok(data, "$"); // getting payload
    char opt = strtok(NULL, "$")[0]; // getting option - 1 in our sample

    // Print
    Serial.println(payload);
    Serial.println(opt);
  }
}

This code results in a stack exception error in the serial monitor. If I remove the last line which prints opt, the payload print works fine and I get 2753192144in the serial output.

I tested this exact code out in a standard C compiler, except instead of the serial read part - I defined a character array with 2753192144$1& and used printf instead of Serial.println. See the code below

#include <stdio.h>
#include <string.h>

int main()
{
    char data[] = "2753192144$1";

    char *payload = strtok(data, "$");
    char opt = strtok(NULL, "$")[0];
    printf("Payload is %s and opt is %c", payload, opt);

    return 0;
}

This code outputs

Payload is 2753192144 and opt is 1

This works fine. Any ideas why the Arduino sketch isn't working?


texts:
I am trying to use Serial reading from a python serial code (which is running on my Jetson Nano) in my project, but in some loop in my code, my data is receiving wrong.

I use Serial.readBytesUntil() function for interrupt-like reading.
I use standart blue mini-USB cable for communication.
My Arduino Nano also connected a nRF24L01 module with SPI.
Baudrate is 9600 for both devices. I tried 115200 but there is no difference.
The data loss is about %10 of all loops with both test codes (image-1, image-2).
There is no positive difference when I use RX/TX pins on both boards with level shifter.
When I use the test code in my main code with USB connection, the data loss increases %50 of all loops. But Arduino serial monitor is fine like image-3.
When I use the test code in my main code with RX/TX pins, Arduino serial monitor looks like image-4 and Arduino IDE gives error like image-5.

Here is my receiver test code on my Arduino Nano.

void setup() {

  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  while (!Serial) {}

}

void loop() {
  char buffer[4];
  int deger = 0;
  if (Serial.available() > 0) {
    int size = Serial.readBytesUntil('\n', buffer, 4);

    if (size == 4) {
      Serial.print("deger: ");
      Serial.write(buffer);
      Serial.print("  size: ");
      Serial.print(size);

      // Bytes to integer
      deger = (buffer[1] - 48) * 100 + (int(buffer[2]) - 48) * 10 + (buffer[3] - 48);
      if (buffer[0] == '1') {
        deger = -1*deger; }

      Serial.print(" Sayi: ");
      Serial.println(deger);
      }

    if (deger < 0) {
      digitalWrite(LED_BUILTIN, HIGH);
    }
    else {
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
}

And the python serial transmitter test code.

import serial

ser = serial.Serial('/dev/ttyUSB0',baudrate=9600,timeout=10)
while True:
    hata = -58

    if hata > 0:
        hata = str(hata)
        if len(hata) == 2:
            hata = '00' + hata
        elif len(hata) == 1:
            hata = '000' + hata
        else:
                hata = '0' + hata    #Pozitive, Added 0
    elif hata < 0:
        hata = -1 * hata
        hata = str(hata)
        if len(hata) == 2:
            hata = '10' + hata
        elif len(hata) == 1:
            hata = '100' + hata
        else:
            hata = '1' + hata    #Negative, Added 1
    else:
        hata = str(hata)
        hata = '000' + hata

    # For every loop, sends 4 character and "\n"  Example: 1058\n
    gonder = hata + '\n'       # For readBytesUntil function
    ser.write(gonder.encode('utf-8'))
    print(gonder.encode('utf-8'))

image-1: Arduino test code serial monitor screenshot

image-2: Python test code serial terminal screenshot

image-3: Arduino main project code monitor with USB cable screenshot

image-4: Arduino main project code monitor with RX/TX pins on GPIO screenshot

image-5: Arduino main project code IDE error

So, what did i do wrong?
Thank you!


texts:
I'm new to networking and working with ESP8266. I have successfully setup my ESP8266 and can program it from Arduino IDE (tested a blinky code).

I want to send some data from a Python script running on my PC to ESP8266. Similar to a setup where use PySerial in Python, open a COM port and send my serial data to an Arduino. Arduino will parse my data bytes and will perform some action. Now, I am trying to achieve the same with ESP8266 and UART replaced with wireless communication.

First, I would like to connect my PC to ESP which will have its own SSID and password. Once connected, I would like to send my data bytes from Python script to ESP8266 wirelessly. Now, similarly, ESP will parse this received data and perform some function (like control its GPIOs).

How can I achieve this? It seems like a pretty simple task, but I'm really confused with what mode I've to use (AP? Client? Server?). What protocol for communication is the best (TCP? MQTT?). What do functions like Handle client/root do? I understand I've to use socket programming on Python, how to do that specifically in my case? How do I buffer my incoming data on ESP, so that I don't miss the bytes?

Could anyone please explain using an analogy with wireless communication and UART? Any links to tutorials will be helpful too. There are some tutorials online where they do this using a HTTP server and control the GPIOs from the browser, but no, I don't want this. I just simply want to send my data as I would with COM Port/UART/Arduino!


texts: Help with multi function momentary buttons

texts:
I'm using the PunchThrough Bean and trying to build a two button project that has multiple functions. The idea is the user can press button 1 or button 2 for either short or long presses, or they can press both buttons simultaneously for a short or long press. This would give the user up to 6 different functions. Below is my code. I can get button 1 or button 2 press to work, but can't get pressing both to work. Also, I can't figure out how to have a function depending on how long a button sequence was pushed. Any help would be greatly appreciated.

const int btn0 = 2;
const int btn1 = 3;

void setup() {
  Bean.enableWakeOnConnect(true);
  Bean.enablePairingPin(true);
  BeanHid.enable();
  pinMode(btn0, INPUT_PULLUP);
  pinMode(btn1, INPUT_PULLUP);
}

void loop() {
  bool connected = Bean.getConnectionState();
  pinMode(btn0, INPUT_PULLUP);
  pinMode(btn1, INPUT_PULLUP);

  if (connected) {
    int btn0State = digitalRead(btn0);
    int btn1State = digitalRead(btn1);

    if ((btn0State == LOW) && (btn1State == HIGH)) {
      Bean.setLed(255, 0, 0);
      Serial.print("up");
      BeanHid.sendKey(KEY_UP_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

    if ((btn1State == LOW) && (btn0State == HIGH)) {
      Bean.setLed(0, 255, 0);
      Serial.print("down");
      BeanHid.sendKey(KEY_DOWN_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

    if ((btn1State == LOW) && (btn0State == LOW)) {
      Bean.setLed(0, 0, 255);
      Serial.print("right");
      BeanHid.sendKey(KEY_RIGHT_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

  }
}


texts: Maximum frequency that can be converted with Arduino Uno?

texts: Arduino Uno Board use successive approach ADC of 12 bits and 16 MHz frequency clock. What is the maximum voice frequency can be converted using arduino uno board? I want the step by step solution with calculations.


texts: Arduino Digital Input. Trigger HIGH by 12V to 36V

texts: I want to build a small circuit that will switch a LED on (for arguments sakes) when the cars ignition gets switched on. But I want to make it versatile so I can work with between 12V - 36V (Cars, Trucks, etc). What would be the best to read the Ignition status via the arduino. Know I have thought of an idea by working with voltage divider. Basically taking the principal of reading voltage Instructable Example and working from there. Any thoughts?


texts: Can stack size be determined by free heap?

texts:
i have NodeMCU with es8266 onboard on it. I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen. So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

one tiny question here: can Serial.println("asd asd") cause memory fragmentation?


texts: NodeMCU burned, did I something fundamental wrong?

texts:
I have a NodeMCU where I connected a LED strip (WS2812b, which operates at 5V).

NodeMCU is powered via USB 5V. The used power adapter can supply 2.5A max.

I don't have a separate power supply for the LED strip yet, so I connected it to VIN/GND of the NodeMCU.

That worked.

Yesterday, I took the NodeMCU (without led strip) to my PC and uploaded an updated sketch.
After that, back in the living room, I connected the NodeMCU with the led strip and the USB power supply.
I didn't need an ambilight at the moment so I left it off.
After 5 minutes, I smelled something burned. As you can see in the second image, the component below ground is burned.

I had this setup successful running for a week (with ambilight turned on for several hours) and had no issues at all.

Did I something fundamental wrong?
Any guess, why it works flawless and then suddenly burned after just 5minutes?

Any tip/suggestion is very appreciated!

The white component on the right is a DHT22 temperature sensor and has been added for completeness.

The resistor and LED on the right are not used, they were just plugged in from a previous setup.

Best regards

Casper


texts:
I've designed an PCB and due tot the delivery times, I kinda want to order it right now.
I don't yet have the components, so I haven't actually tried it on a breadboard.

Now I'm unsure if the PCB would work, as this also is my first try in PCB design.

It's a single-sided PCB.
All parts (should be) through hole.
I would be using SoftwareSerial since the ATTiny does not have serial (Rx/Tx).

[TL:DR] Would this PCB work?

Some points of which I'm unsure, or might be a problem:

Is the spacing of the board/lines to other components/side big enough?
Should I use a copper/ground fill? Which and why?
Are the rounded-off traces actually better as sharp edges?
It says: 36mm by 15mm isn't this too small to fit all those components?
Can I actually use the RESET pin as other functions (without changing fuse bits)?
Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Breadboard

Schematic

Layout

File

If someone needs the file:
It's opensource, no restrictions. Would be nice to give me some credits/donation, but you can freely use it for even commercial projects.
Download below:

https://www.dropbox.com/s/lggjg5fxd6s3kqc/ATTINY485.fzz?dl=0

Some credits to Nick Gammon, I've used his schematics as a reference (especially on the TX enable pin, which was quite smart, using only 1 pin).

Version2!

Changes:
 - replaced the "V" shape.
 - pull-up on the reset pin.
 - decoupling capacitors

EDIT: It's better not to use a pull-up resistor on the reset line. The ATtiny85 has this internally.


texts: Maximum signal frequency obtained at the gpios of arduino mega 2560

texts: Is it possible to obtain the rectangular pulse signals of freuency 10 MHz simultaneously at the GPIOs of arduino mega 2560?


texts: Combining & averaging magnetometer values

texts:
I am trying to measure a users 'hand steadiness' in order to control a video game character in UNITY3D. I am using a MinIMU-9 Gyro/Accelerometer/Compass linked with Arduino. I can measure pitch/roll etc in Arduino...and I have passed previous Arduino measurements into Unity via the serial command but I am l trying to do two things:
1. simplify & reduce noise in the data coming from the magnetometer reading before I pass it into Unity by taking an average of every 10 magnetometer readings.
2. Combining the three magnetometer values to get one overall variable or measurement that can be passed into unity.

This is the demo Sketch I have but I'm not sure how to script the addition of the x,y,z magnetometer values:

#include <Wire.h>
#include <LSM303.h>
LSM303 compass;
char report[80];
void setup()
{
  Serial.begin(9600);
  Wire.begin();
  compass.init();
  compass.enableDefault();
}
void loop()
{
  compass.read();
  snprintf(report, sizeof(report), "A: %6d %6d %6d    M: %6d %6d %6d",
    compass.a.x, compass.a.y, compass.a.z,
    compass.m.x, compass.m.y, compass.m.z);
  Serial.println(report);
  delay(100);
}

This is the type of 'averaging script' I would like to add in somewhere but I'm not sure where exactly to place it:

for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
    reading[i] = compass.m.y;
    delay(2);
  }
  for(int i = 0; i < 10; i++){   //average the ten readings
    finalMagYreading += reading[i];
  }
   finalMagYreading
 /= 10;

Any help with this would be great.


texts:
My problem lies in the fact that I can not stop the "void loop" function and more accurately "StatInDoor". I have to make sure that the "ButtonOpenDoor" works independently of "ButtonCall". If someone presses the "ButtonCall" button then the "ButtonOpenDoor" button must work in progress, and if the "ButtonCall" button is pressed, the "ButtonOpenDoor" button must stop playing the melody.

My idea for this this:

int StatOutDoor = digitalRead(ButtonCall && ButtonOpenDoor);

or:

if(StatOutDoor == LOW && StatInDoor = LOW){
   PlayMelody();
}

But it does not work :(

Full code:

#include "pitches.h"

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};
int ButtonCall = 4;
int buzzer = 8;
int ButtonOpenDoor = 7;
int RelayModule = 12;

void PlayMelody() {
  for (int thisNote = 0; thisNote < 8; thisNote++) {
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(buzzer, melody[thisNote], noteDuration);
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    noTone(buzzer);
  }
}

void setup(){
  pinMode(ButtonCall, INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(ButtonOpenDoor,INPUT);
  pinMode(RelayModule,OUTPUT);
}

void loop() {
  int StatOutDoor = digitalRead(ButtonCall);
  if(StatOutDoor == LOW){
    PlayMelody();
  }
  int StatInDoor = digitalRead(ButtonOpenDoor);
  if (StatInDoor == HIGH) {
    digitalWrite(RelayModule, HIGH);
  } else {
    digitalWrite(RelayModule, LOW);
    delay(3300);
  }
}

Can someone help with this? (Sorry for my bad English).


texts:
I'm using arduino Ethernet shield 2 form arduino.org and the arduino IDE 1.7.10 also from arduino.org
the code is :

#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp2.h>
#include <Twitter.h>
#include <util.h>

#include<SPI.h>

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

}

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

}

and it is giving the following Error :

Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

Error compiling.

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

after Enabling Show verbose output I got :

Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

Build options changed, rebuilding all

Using library Ethernet2 in folder: C:\Program Files\ArduinoOrg\libraries\Ethernet2

Using library SPI in folder: C:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI

C:\Program Files\ArduinoOrg/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\cores\arduino -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\variants\standard -IC:\Program Files\ArduinoOrg\libraries\Ethernet2\src -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp -o C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp.o

UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

Error compiling.

any Help please

These libraries came with the IDE and were not added by me and all the includes
were added automatically after using Sketch --> Import Library --> Ethernet2


texts:
I have a board without network connection, then I bought an SP-WROOM-32 dev kit because it has network connection ability.

Is there any way that I use esp32 as a secure socket (just like calling socket_connect() and the ESP will be used?)

I know that my board can control the ESP with AT commands but I want a native way.

Thank and have a nice day.


texts: What's the point of a USB to Serial converter in Arduino Uno?

texts:
I am trying to understand how an Arduino Uno communicates with a PC and why it does so.

As far as I understand, an Arduino can be programmed to communicate with a PC only via a COM interface. At the same time, an Arduino Uno uses a physical USB interface to connect to a PC and it has a USB-serial converter onboard. So data sent from the board is converted from COM to USB to be transferred to the PC where USB data is converted to COM by a device driver to be read by a COM-port listener.

Why does this COM-related stuff is needed if the Arduino already uses the USB stack for connection? And is the Arduino able to emulate a keyboard and mouse if it has to use interrupts for this, so it has to act like USB device without using COM?


texts: Ok I'm stupid when it comes to coding. I have a simple project that I need some help with. Is it possible to make neopixle change what animation runs via multiple switches. Example they stay off till switch is flipped then if a different switch is flipped they run a different animation and vice versa.