texts: Sketch will not start with external power source

texts:
NOOB Question: when my Uno is connected to an external power source it will not start running the uploaded sketch. The Arduino web site says it's because the RX pin is not connected and then gets random data.

The site suggests grounding the RX pin using a resistor (granted it suggests a 10K and I used a smaller one ) or connecting it to the TX pin.

From Why doesn't my sketch start when I power up or reset the Arduino board?

  Most likely because you are sending serial data to the board when it
  firsts turns on. During the first few seconds, the bootloader (a
  program pre-burned onto the chip on the board) listens for the
  computer to send it a new sketch to be uploaded to the board. After a
  few seconds without communication, the bootloader will time out and
  start the sketch that's already on the board. If you continue to send
  data to the bootloader, it will never time out and your sketch will
  never start. You'll either need to find a way to stop serial data from
  arriving for the first few seconds when the board powers (e.g. by
  enabling the chip that sends the data from within your setup()
  function) or burn your sketch onto the board with an external
  programmer, replacing the bootloader.

From Why doesn't my sketch start when I'm powering the board with an external power supply? (Arduino Diecimila or earlier)

  Because the RX pin is unconnected, the bootloader on the board may be
  seeing garbage data coming in, meaning that it never times out and
  starts your sketch. Try tying the RX pin to ground with a 10K resistor
  (or connecting RX directly to the TX pin).

Both failed for me.

What should I do?


texts: How do I turn a number of pins to high and then off after 5 seconds based on a serial command

texts:
I have an Arduino sketch where I'm sending commands over serial, and as a result turning pins from low to high. What I'm looking to do is have those pins turn high for 5 seconds and then turn back to low. I was looking for a time or scheduling library for Arduino that allows multiple timers at once and lets you pass a parameter (at least I think that's what I need).

In other words, I would like to implement a "doAfter" method and pass the function it is calling a pin number.


texts: Arduino clone CH340G (ATmega328P), MIDI over USB

texts:
I just bought my first Arduino compatible device, and I am greatly enjoying it. I finally could not resist the urge after going to an Arduino meetup, where someone showed me their Teensy connected to their laptop and reacting to MIDI signals over USB.

Not knowing anything, I bought my clone and soon learned about the whole CH340G limitation where it doesn't "just work" (I cannot simply use the USBMIDI Arduino library), and instead I need to run a software MIDI-serial converter command (ttymidi) in order to send the signals to my Arduino clone.

I've been reading up a bit (the amount of information out there is perhaps too vast and often outdated or simply doesn't exactly solve my problem) and have learned of V-USB and the project V-USB-MIDI but I am really out of my element here and do not know how to approach this to get it all working (since it is not just an Arduino sketch and .h header). Or even if this is a solution to my problem. I've read about some solutions which require using an AVR via some of the pins (as opposed to over USB) since you have to reprogram the chip in such a way that it no longer is programmable over USB once the sketch is uploaded, but if I understood it correctly, you can't do even this on the CH340G.

In any case, are there any examples of getting this working? A sketch or something? I downloaded the latest V-USB release, but I really don't want to make a mistake that will brick or otherwise ruin my device.

Basically: I want to just upload my MIDI sketch (with whatever necessary modifications or code) such that I do not need ttymidi to have the device recognized as a MIDI device (over USB) that I can just "plug 'n' play".


texts: Combining code for multiple sensors in one program (Arduino)

texts:
I need to operate 2 different sensors (gas and DHT11) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together.

Here are the sketches:

Gas sensor MQ2 code :

int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);

This is the DHT11 code :

#include <SimpleDHT.h>

int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
    // start working...
  Serial.begin(9600);
  Serial.println("Temperature and Humidity Data");
}

void loop() {

  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}


texts: Can I connect a camera without a shield?

texts:
I have an Arduino Uno and an ArduCAM-mini 2MP camera:

http://www.arducam.com/tag/arducam-mini/

Is it possible to connect this camera, or similar cameras, to the arduino without a shield?  The only tutorials I've found use a shield.

edit - here is what my cam looks like:


texts: Can I force a function to live in the boot sector without overwriting the bootloader?

texts: Not for any practical purpose but just out of curiosity, I want to abuse the flash memory and write it dynamically at run-time.  This is, in a sense, what the bootloader does.  If I understand it, the only way to modify flash is to do so from instructions written to the boot sector.  Is it possible to stick a simple function in there that writes to flash memory, and call it from running code?  If so, how do I put it there?  I have no issue with calling functions from function pointers, so I don't think I'll have an issue actually calling the function once I get there, but I need to know how to stick into flash in the first place.


texts:
I'm trying to read from the EEPROM and combine the information and send it out over SoftwareSerial using write() function but i'm getting the following error

error: invalid operands of types 'const char [3]' and 'const char*' to binary 'operator+'

void loop()
{
  const char* eTest1 = EEPROM.read(1);
  const char* eTest2 = EEPROM.read(2);
  const char* eTest3 = EEPROM.read(3);

  char combinedVal[] = eTest1+":"+eTest2+":"+eTest3;
  bluetooth.write(combinedVal);
}


texts: Is this method to a String from a function going to cause memory corruption?

texts:
I'd like to define a function such that I return a string and a boolean indicating whether the result is valid. Like this:

bool getStringOrTimeout(String *s) {
  ...
  if (timed_out) {
    return false;
  } else {
    *s = String(<some value>);
    return true;
  }
}

Is this going to cause a memory problem because the string is allocated on the stack and deallocated when it leaves scope, or is this okay?


texts: storing 600 unsigned int values in an array and find minimum and maximum values

texts: I am reading an ASCII serial data values from a sensor and storing it in an unsigned integer variable. The values are ~45000 to 50000 range. I need to store 600 values and then find the minimum and maximum. after 600 values reached the oldest value is being replaced with the new value. The array size required is 600 which is approx.1200Bytes of the size of storage. I'm using Atmega 2560. I would like to know is it possible to store all 600 values in SRAM or do I need to use EEPROM memory?


texts: data type error on sensor data to ethernet client

texts:
I'm having a hard time debugging this piece of code, and i'm hoping someone can point out where i am making the mistake.

My serial output is:

connected
GetData()
got data...
next stage...

I've tested with a simple network client that loops sending a hello world, and it works fine. Every time this code halts after attempting to send a value to the client. I know that  getData() is causing the issue, but i cannot work out why, or how to best resolve it.
(apologies for the code dump, i want to be thorough)

#include <LiquidCrystal.h>
#include <dht11.h>
#include <SPI.h>
#include <Ethernet.h>
dht11 DHT11;
#define DHT11PIN 8

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server(192,168,1,100);
IPAddress ip(192,168,1,50);
EthernetClient client;

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

const int trigPin = 6;
const int echoPinOne = 7;
const int echoPinTwo = 8;
const int echoPinThree = 9;
const int echoPinFour = 10;

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
  delay(1000);

  //Network
 if (Ethernet.begin(mac) == 0) {
    Serial.println("DHCP FAIL");
    Ethernet.begin(mac, ip);
  }
  delay(1000);
  Serial.println("connecting...");
  lcd.setCursor(0, 0);
  lcd.print("connecting");
  connect();
}

void connect(){

    if (client.connect(server, 8080)) {
    Serial.println("connected");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("connected");

    client.println("hello server");
    client.println();
    delay(500);
    lcd.clear();
  }
  else {
    Serial.println("connection failed");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Connection Failure");
  }
  delay(500);
}

void loop() {

   //network
  if(!client.available()){
    Serial.println("lost connection!-restart");
    lcd.println("Disconnection");
    client.stop();
    connect();
  }
  else {

    int inp[5];
    getData(inp);
    Serial.println("next stage...");
    char *output = (char *) &inp[0];
    client.println(output);

    client.println("first");

    Serial.println("sent first...");

    //here repeats the same process for the other sensors - omitted for clear reading

  }
   //end network

   delay(500);
}

void getData(){

Serial.println("GetData()");
long durationThree, inchesThree, cmThree = 0;
long durationOne, inchesOne, cmOne = 0;
long durationTwo, inchesTwo, cmTwo = 0;
long durationFour, inchesFour, cmFour = 0;

//SENSOR ONE
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinOne, INPUT);
durationOne = pulseIn(echoPinOne, HIGH);

delay(100);

//SENSOR TWO
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinTwo, INPUT);
durationTwo = pulseIn(echoPinTwo, HIGH);

delay(100);

//SENSOR THREE
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinThree, INPUT);
durationThree = pulseIn(echoPinThree, HIGH);

delay(100);

//SENSOR FOUR
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinFour, INPUT);
durationFour = pulseIn(echoPinFour, HIGH);

//DISTANCE CALCULATION
cmOne = microsecondsToCentimeters(durationOne);
cmTwo = microsecondsToCentimeters(durationTwo);
cmThree = microsecondsToCentimeters(durationThree);
cmFour = microsecondsToCentimeters(durationFour);
//Serial.println("sending...");
//char *out = (char *) &cmOne;
//Serial.println(out);
//client.println(out);
//Serial.println("sent!");      used this to test - same issue

Serial.println("got data...");
inputBuf[0] = cmOne;
inputBuf[1] = cmTwo;
inputBuf[2] = cmThree;
inputBuf[3] = cmFour;

}

long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}


texts: Stepper motor is only moving one step at a time with an IR sensor

texts:
I am trying to get both the motors to run simultaneously once the motion detector senses an obstacle. Both motors run fine by themselves but when I implement the sensor the motors only move one step per motion detected.

Arduino Mega (ATMega 2560)
(2) NEMA 17 stepper motor/ A4988
Digital IR Sensor Module

#include <Arduino.h>
#include <avr/io.h>
#include <AccelStepper.h>

AccelStepper stepper(1,5,4); // w/Driver (1,Step, Direction)
AccelStepper stepper2(1,9,8);

const int pin_ir_in = 3;
int prev_state = 1;
int curr_state = 1;
int counter =0;

void setup() {
  Serial.begin(9600);
  pinMode(6,OUTPUT); // Enable
  pinMode(10,OUTPUT);

  digitalWrite(6,LOW); // Set Enable low
  digitalWrite(10,LOW);
}

void loop() {
  digitalWrite(6,LOW); // Set Enable low
  if (stepper.distanceToGo() == 0)
  {
    delay(1000);
    stepper.moveTo(100);
    stepper.setMaxSpeed(200);
    stepper.setAcceleration(100);

  }

   digitalWrite(10,LOW); // Set Enable low
     if (stepper2.distanceToGo() == 0)
  {
    delay(1000);
    stepper2.moveTo(100);
    stepper2.setMaxSpeed(200);
    stepper2.setAcceleration(100);

  }

int curr_state = digitalRead(pin_ir_in);
if (curr_state != prev_state)
{
  if (curr_state == 0)
  {
    stepper.run();  // Actually makes stepper move
    stepper2.run();
    delay(500);
  }
  prev_state = curr_state;

}

}


texts: How to put Arduino Nano in low power sleep mode (<0.05mA)

texts:
I'm trying to put an Arduino Nano in low-power mode using this guide: Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery.
The article suggests 3 things: use the Low-Power library from Rocketscream, cut the power to the power LED, and remove the voltage regulator.
So far I've only done the first two and reduced the clock speed to 8 MHz.
The important part of the source code that puts the Arduino in deep sleep looks like this:
void setup() {
  CLKPR = 0x80; // (1000 0000) enable change in clock frequency
  CLKPR = 0x01; // (0000 0001) use clock division factor 2 to reduce the frequency from 16 MHz to 8
}

void loop() {
  // Go to sleep until the next scheduled wake up
  int32_t waitSeconds = 60;
  while (waitSeconds > 0) {
    period_t waitFor = SelectWaitTime(waitSeconds);
    LowPower.powerDown(waitFor, ADC_OFF, BOD_OFF);
    waitSeconds -= PeriodToSeconds(waitFor);
  }
}

period_t SelectWaitTime(int32_t secondsToWait) {
  if (secondsToWait >= 8)
    return SLEEP_8S;
  else if (secondsToWait >= 4)
    return SLEEP_4S;
  else if (secondsToWait >= 2)
    return SLEEP_2S;
  else if (secondsToWait >= 1)
    return SLEEP_1S;
}

In essence, sleep for up to 8 seconds, remove the seconds from the counter, then sleep again.
So far I've only scratched off the trace to the power LED and haven't removed the voltage regulator. According to the article above, this should reduce the power consumption to around 0.05 mA but I get around 1.7 mA, which is over 30 times more!
Electrically, I only have a MOSFET as a power switch connected to one of the analog pins (I use it as a digital output) and another controller, connected to the I2C pins (the Arduino acts as Slave). The other controller is turned off through the MOSFET when I take the measurements. Physically removing the connections doesn't change the consumption, so I don't think any of that is related.
Is there something I did wrong? What can I do to achieve power consumption similar to the one in the article?


texts: Is there anything special about Arduinos?

texts:
I've been using the stm32f4 discovery up until now but I've heard Arduinos are easier to use. While looking for an Arduino Genuino Uno Rev3 board, I was told to get a knock off instead.

Is there any real difference between Arduino boards and other knock off micros with similar specs?
I really just want to get a feel for what it's like using an 'easier' micro. It doesn't need to be extra special.


texts:
I have a 0.96" OLED display hooked up to my Arduino Mega via SPI. I installed the Adafruit library and GFX library. I can run through the little graphical demo from Adafruit just fine as well as display static text with no problem.

However, I am trying to put together a project I thought would be simple and straight forward. I am trying to use a DHT22 to collect temperature and humidity and then display it on the OLED. The problem I am running into is that the Arduino freezes after an indeterminate amount of time. The most it has been able to run is about 6 minutes.

Here is the code I am using:

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

#define DHTPIN 7
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// If using software SPI (the default case):
#define OLED_MOSI   8
#define OLED_CLK   9
#define OLED_DC    10
#define OLED_CS    11
#define OLED_RESET 12
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH  16

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

long previousMillis = 0;
long interval = 5000;

    String temperature;
    String humidity;

void setup(){
  dht.begin();

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

  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC);

  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);

  display.println(" Madgayrah");
  display.display();
  while(millis()<2000);
}

void loop() {

  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;

    float h = dht.readHumidity();
    float f = dht.readTemperature(true);

    if(isnan(h) || isnan(f)){
      int x = 6;
      String dashes = "";
      for(int y=1; y<=x; y++){
        dashes += "-";
      }
      temperature = humidity = dashes;
    }else{
      temperature = String(f)+(char)248;
      humidity = String(h)+"%";
    }

    display.clearDisplay();
    display.setTextColor(WHITE);
    display.setCursor(0,0);

    display.setTextSize(1);
    display.println(String(previousMillis/1000));
    display.println("");

    display.println("Temperature:");
    display.setTextSize(2);
    display.println(temperature);

    display.setTextSize(1);
    display.println("Humidity:");
    display.setTextSize(2);
    display.println(humidity);

    display.display();
  }
}

In my attempt at debugging I discovered that NOT printing out the temperature and humidity variables allows the program to run indefinitely. However, for some reason turning on either one of those lines and printing out that variable leads to the issue of the Arduino freezing.

ADDITIONAL INFORMATION:
I am using a 12 volt external power supply hooked up to the barrel of the Mega. The Mega is providing 5 volts and ground to a bread board which powers/grounds both the OLED and the DHT22.

Any ideas as to what could be causing the freezing issue on what "should be" a simple and straightforward project? Thanks.


texts: Extracting a specific sequence of characters from an array

texts:
I have a character array called storebuffer that contains data from a POST submission and its in the format ssid=abcdef&pswd=ghijk. I wanted to extract everything after ssid= into one array called acqSSID and the portion after &pswd= into another array called acqPaswd. I tried using this but it does not seem to be working. MAX_STORE_BUFFER_LEN is 255. Can anyone help?

int ctr = 0;
for (ctr = 5; ctr < MAX_STORE_BUFFER_LEN; ctr++)
{
  if ( (storebuffer[ctr] == '&') && (storebuffer[ctr+1] == 'p') && (storebuffer[ctr+2] == 's') && (storebuffer[ctr+3] == 'w') && (storebuffer[ctr+4] == 'd') && (storebuffer[ctr+5] == '=') )
  {
    break;
  }
  acqSSID[ctr] = storebuffer[ctr];
}

Serial.print("acqSSID: ");
Serial.println(acqSSID);
Serial.print("ctr: ");
Serial.println(ctr);


texts: Is it possible to directly communicate USB D+ D- to Arduino Mega serial port TX RX?


texts: How can I set 4 Arduino Leonardo PWM-ports between 200Hz and 1kHz?

texts: I've noticed that I can set D9, D10, and D11 to around the timer 1 can be set to ~244Hz. However I need 4 ports that are between 200-1000Hz but I have been unable to figure out how to find the last one. I can't really touch timer 0 as they control millis etc.


texts: Help with Arduino Micro Keypress Algorithm

texts:
Greeting, first time Arduino user here.

So I am using the Arduino Micro as an HID keyboard device. It accepts arbitrary input from a Node-JavaScript program I am running (so I have full freedom in in the data transferred to the micro).

The goal is for the data transmitted to the micro to include information about a keypress: whether it was pressed or released and which key it is. The serial connections are all fine and dandy - I just have questions regarding the key pressing logic.

As far as the JavaScript program goes, a key down is detected based on the keyCode, not the character code so when tapping “a”, character code  97, the Arduino micro is receiving “A”, character code 65 since the JavaScript detected keyCode is 65. So that all sounds like problems with JavaScript (which it is), but remember that I have freedom in portraying the information sent to the micro.

That being said, instead of detecting by keyCodes and character codes in JavaScript, I could just transmit the letter e.g. “a” with some identifier for press/release such as “+a” for release and “-a” for press. My problem here is how would I handle modifier keys using the Keyboard library.

Should I handle character keys and modifiers keys separately i.e. Keyboard.write for characters and Keyboard.press/release for modifiers or are there cases where it would make sense to press and hold “a” (which would also be different than pressing and holding “A”)?

Below is my original code using keyCodes and “u/d” identifiers to denote up or down (which I am thinking now that “u/d” could be easily confused as a letter if I decide to transmit characters as characters:

/*
  Receives from the hardware serial, sends to software serial.
  Receives from software serial, sends to hardware serial.

  The circuit:
   RX is digital pin 10 (connect to TX of other device)
   TX is digital pin 11 (connect to RX of other device)

  Not all pins on the Leonardo and Micro support change interrupts,
  so only the following can be used for RX:
  8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
*/

#include <SoftwareSerial.h>
#include <Keyboard.h>

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  // Set the data rate for the SoftwareSerial port
  rpiSerial.begin(115200);
  // initialize control over the keyboard:
  Keyboard.begin();
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Keyboard Serial Connection Established");
}

String keyCode = "";
char state;

void loop() {
  while (rpiSerial.available() > 0) {
    // "Type" via keyCodes (recommended for modifiers)
    // https://www.arduino.cc/en/Reference/KeyboardWrite not behaving as expected

    int data = rpiSerial.read();
    if (isDigit(data)) {
      keyCode += (char)data;
    }

    if (isAlpha(data)) {
      state = (char)data;
    }

    if (data == '\n') {
      Serial.print(state);
      Serial.println(keyCode.toInt());

      if (state == 'd') {
        Keyboard.press(keyCode.toInt());
      }

      if (state == 'u') {
        Keyboard.release(keyCode.toInt());
      }

      keyCode = "";
      char state;
    }
  }
}

I have also noticed that the data from the serial connection parsed by the micro is sometimes incorrect i.e. a keyCode will be misidentified. For instance, by repeatedly pressing “a” through my JavaScript program, the JavaScript program will consistently identify keyCode 65 yet Arduino will identify the received data as keyCode 65 most of the time and then randomly keyCode 64. This happens with other keys as well and the keyCode doesn’t always happen to be just one less nor does it always occur after “n” presses.


texts: Can I use Arduino TFT LCD Module ILI9341 as a data logger? It has an SD card slot at the back, I wonder if the data will be saved on the SD card? Thanks!


texts:
You know , a simple arduino sketch has no main function , no include preprocess cmds,so I just want to know how arduino IDE convert a sketch to normal C/C++ source code,and what is the source code looks like.

If possible,I also want to use cmd like  g++ -E   to see the .i file genetated after preprocess.How to do it?

ps: my English is poor.


texts: How can I power off a servo the best way? Problems with MG90S servo

texts:
I have a NodeMCU and im trying to control a servo to move from angle A to B and viceversa. The thing is I want to be able to power off the servo after moving so it could stop getting voltage and current. I decided to use an NPN transistor (2N2222A to be more precise) and the servo red cable is connected from one end of the transistor and the other end is connected to the red line in my breadboard while the middle pin is connected to a pin in the NodeMCU. The thing is, it seems to work with a SG90 perfectly but when an MG90S is connected it doesn't move and you can hear a faint clicking from the servo. When the MG90S is instead connected directly to voltage line it works. I don't understand what the problem is. I also implemented the servo.detach(); function and it works but I don't know if it truly shuts off power to the servo like using a transistor would.
if (buttonState2 == HIGH) {
  digitalWrite(LED2, HIGH);
  digitalWrite(transistor2, HIGH);

  for (pos2 = 90; pos2 < 180; pos2 = pos2 + 1) {
    servo2.write(pos2);
    delay(15);
  }
  digitalWrite(transistor2, LOW);
  digitalWrite(LED2, LOW);
}

This is the code that I have, I would really appreciate some help, Thanks!


texts: Arduino force feedback vibration gamepad

texts:
I'm projecting a gamepad with Arduino Micro. I'm using the Arduino Joystick Library.

I'm building this gamepad for racing games so I need to catch signal like hit_the_wall, hit_another_car.

I wonder how the PC game output the signal of the vibration/force feedback and send throw USB to the gamepad.

I already know that the gamepad drivers and the game have to support this function, but I'm completely lost about how I can catch the input to trigger the vibration engine with Arduino.

I was thinking something about (pseudocode):

input = Serial.read();

if(input == hit_something_signal){

   digitalWrite(engine, HIGH);

}

Now my question is which is this magic hit_something_signal?

UPDATE

I'm reading the PID document and I notice on page number 24 the register addresses to implement the force feedback.

;Start Force Feedback command definitions
USAGE_PAGE (Physical Interface) 05 0F
;Effect Report Definition
 USAGE (Set Effect Report) 09 21
 COLLECTION (Logical) A1 02
 USAGE (Effect Block Index) 09 22
 LOGICAL_MAXIMUM (127) 25 7F
 REPORT_SIZE (7) 75 07
 REPORT_COUNT (1) 95 01
 OUTPUT (Data,Var,Abs)
 .......

In the Joystick.cpp file I notice the HID implementation:

// USAGE_PAGE (Generic Desktop)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x05;
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;

// USAGE (Joystick - 0x04; Gamepad - 0x05; Multi-axis Controller - 0x08)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;
tempHidReportDescriptor[hidReportDescriptorSize++] = joystickType;

// COLLECTION (Application)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0xa1;
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;

// REPORT_ID (Default: 3)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x85;
tempHidReportDescriptor[hidReportDescriptorSize++] = _hidReportId;
.......
......

Do you think should be possible to implement the force feedback part? I do not need to catch all the forces, but run the vibrator engine every time the game sends and input of every kind of force.

The problem is that I'm not an expert about low-level programming and drivers. Do you have any idea?


texts: How do I use the timers on an Arduino Uno R3?

texts: I want to make a simple circuit which returns the time/delay between two, consecutive loud sounds (i.e, a mic reading of ~600) coming from a speaker. I have set up and ADMP 401 microphone for this purpose. How do I measure the time it takes for this application?


texts: I'm new to electronics and have been getting rather into my Arduino. But I don't just like following an instructable to do something. I like to know the math behind it and how it works inside. Now from my understanding the Arduino (Uno R3 for me), has a 200 mA max current. The LEDs I used have a 20 mA current. Now with 64 LEDs, wouldn't this fry my Arduino? This also applies to my LCD screen with a 160 mA current. Am I missing a key secret to going over amperage?


texts: Pin Mappings from Arduino Metro M4 Express Board to SAMD51

texts:
After looking through the internet, I coudln't find any document (not in the datasheet, no nice graphics on google image searches) that showed the mapping between the Arduino breakout board and the SAMD51. Does such a mapping exist?

I'm answering my own question below, but perhaps someone knows of a better table.


texts: I'm trying to compile a code to arudino pro micro, I have the right option for compiling like the port and the type of the board,but I get an error,I can't copy


texts: Faster way to parse a HTTP response in Arduino

texts:
I send a GET http request to a server and get following data back.

HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 16 Nov 2018 16:30:05 GMT
Connection: close

35
{
  "uuid" : "13b29524-7e12-48fb-bbf9-4396aefff45d"
}
0

with the following code I get the header info and the body.

void parseResponse() {
  boolean headerEnd = false;
  byte lineCount = 0;
  String line;
  char endOfLine[] = "\r\n";
  while (1) {
    if (client.available()) {
      char inChar = client.read();
      if (!headerEnd && line.endsWith(endOfLine)) {
        // Just save the first then headers
        if (lineCount == 10) {
          headerEnd = true;
        } else {
          headers[lineCount] = line;
          line = "";
          lineCount++;
        }
      }

      if (line.endsWith("close")) {
        line = "";
        headerEnd = true;
      }

      if (headerEnd && line.endsWith("}")) {
        line.toCharArray(response, sizeof(response));
        client.stop();
        break;
      }

      line += inChar;
    }
  }
}

this thakes 60 - 70ms to parse. Is there a faster way to parse? I think that's slow, for so little text, in the world of AVRs.


texts: Arduino Uno & ESP32 communication using RS485

texts:
I am trying to establish a communication between Arduino Uno ( Master) and ESP32 (Slave) using RS485 protocol (using MAX485 module).
I have successfully done this between two Arduino Unos. SoftwareSerial library is what i am using between two Arduino Unos, now trying with ESP32 and Arduino Uno (using MAX485 module)
.
For ESP32 i have used SoftwareSerial (https://github.com/akshaybaweja/SoftwareSerial) library.

After reading the library and making connection i am not be able to establish a communication between them. Sharing my code below.

Receiver

#include <SoftwareSerial.h>

SoftwareSerial softwareSerial(9, 10);
String str;

void setup()
{

  Serial.begin(9600);
  softwareSerial.begin(9600);

}

void loop()
{

  while (softwareSerial.available() > 0) {

    char inChar = softwareSerial.read();

    if (inChar == '$') {

        str.trim();
        Serial.println("received command" + str);
        memset(&str, 0, sizeof(str));
        Serial.flush();
        softwareSerial.flush();
    }
    else {
        str = str + inChar;
    }

 }

}

Sender

#include <SoftwareSerial.h>

SoftwareSerial swSer1(22, 23, false, 256);
String str;

void setup() {

  Serial.begin(9600);
  swSer1.begin(9600);

}

void loop() {

  String sendCmd = "MSG1$";
  Serial.println("Sending ");
  Serial.println(sendCmd );
  char copy[50];
  sendCmd.toCharArray(copy, 50);
  swSer1.write(sendCmd);
  delay(1000);

}

Here my question is where i am going wrong in this project. Please guide me.

Note : DE AND RE PINS are connected to high for sender device and to low for receiver device as given in the RS485 documentation.


texts: Basic communication between Cotek and Arduino UNO

texts:
I am trying to get a reading from my Cotek through my Arduino and have it display on an LCD screen. When I run the code, though, nothing shows up. I am EXTREMELY new to using pretty much all this equipment so honestly, I have little to no idea what I'm doing. I am not sure if it is a wiring issue, an issue with the code or both. Any and all help is appreciated.

This is how the cotek is wired to the Arduino. The middle red wire (in the middle of the two resistors) is connected to AUX from the cotek. The two outer red wires are connected to the SDA and SCL of the cotek and their corresponding blue wires are connected to the SDA and SCL of the Arduino (the two resistors are 2KOhm pull-up resistors). The blue wire on the bottom is connected to the GRND of the cotek which is also connected to GRND of the Arduino.

This is my code using the I2C protocol:

#include <LiquidCrystal.h>
#include <Wire.h>

int analogPin = 5;
char address= 0;
int numBytes = 2;
char val = 0;
int debug = 5;
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {
  // put your main code here, to run repeatedly:
  Wire.requestFrom(address, numBytes);
  while(Wire.available())
  {
    val = Wire.read();
    Serial.print(val);
    lcd.setCursor(0,0);
    lcd.print(val);
  }
  //perform function to change val from hexadecimal to decimal number here
  delay(500);

I am pretty sure the LCD is wired correctly to the Arduino as I was able to communicate to it previously without using the Cotek. In any case, it doesn't matter as 'val' doesn't even appear on the serial monitor.

Again, any help would be appreciated. Thanks!


texts: Communication Protocol Best Practices and Patterns

texts:
Every time I design a serial protocol to be used between two arduinos, I feel a bit like I'm reinventing a wheel. I wonder if there are any best practices or patterns people follow. This question is less about the actual code, but more about the format of the messages.

For example, if I wanted to tell an arduino to flash it's first LED 3 times I might send:

^L1,F3\n

'^': starts a new command
'L': Defines the command, (L: target this command to an LED)
'1': Target the first LED
',': Command line separator, new value in this message to follow
'F': Flash sub-command
'3': 3 times (Flash the LED three times)
'\n': End the command

Thoughts? How do you usually approach writing a new serial protocol? What about if I wanted to send a query from arduino 1 to arduino 2 and then receive a response?


texts: Short battery life concern with Arduino Pro Mini

texts:
I am using an Arduino Pro Mini with a L293D H-bridge driver to drive a bi-directional motor. The system takes input from a capacitive sensor which is constantly looking for a trigger. I don't have any low power optimization in the code. I was using Arduino UNO before which lasted for one day with a 9V battery. I switched to Arduino Pro Mini for longer battery life but the battery lasted for one day in that case as well.

Can anyone please help me understand what could be the possible reason for higher power consumption than normal for Arduino Pro Mini?

Thanks in advance for your help!

Niloy


texts: Arduino to send sms one time only when a button is pressed

texts:
The LED_UPDATE() is called in my loop() function, I implemented it (tried anyways),
to send sms as shown in the code such that  only one sms is sent , because as the loop() keeps calling LED_UPDATE(), it's going to keep sending an sms every time (yep you guessed it, very bad for credit :o )

any tips on how I can get around this or what i'm doing wrong in my code would be much appreciated.

p.s. nearly left my mobile phone in the code lol

void LED_UPDATE(int state)
{

int count; // initialized to zero, once program runs it automatically enter state ==1
if (state == 1)
{

    digitalWrite(RED_PIN, LOW);
    digitalWrite(GREEN_PIN, HIGH);
    count=0;
}
else if (state == 2)
{
  count+=1;
  Red_Blink();

  if(count == 1 )
  {
    sms.SendSMS("086XXXXXXX", "PANIC BUTTON PRESSED, Subject needs help!!!");
  }

}


texts: How does Peggy2 drive rows with 74HC154 Decoder?

texts:
Trying to program Evil Mad Scientist's Peggy 2 board without their Library.
The board drives a LED Matrix with

Source  74HC154 Decoder
Sink    STP16CPSO5  LED Sink Driver

Schematic

What has me confused is the 74HC154 Outputs can only have one output set to Low at at time. See table below. This means all but one row is "on". Isn't this backwards?  Shouldn't all outputs be low except one that is high?  Selecting what row you want on, rather than selecting what row you want off.  It looks more like the 74HC154 is a Sink.  Thanks.


texts: Teensy to Teensy serial communication via USB connector

texts:
I have 2 Arduino Teensy 3.2 boards that I'm trying to implement serial communication between the 2 boards.  I have successfully done this by connecting RX1 of the 1st Teensy with TX1 of 2nd Teensy and TX1 of 1st to RX1 2nd.

However I was wondering if I could send serial messages between the Teensys i.e. do the same thing, by connect the 2 Teensys via the USB port?  Or is this USB port reserved to connecting the Teensy to a computer?


texts: How to send multiple data from PC to arduino

texts:
I have a project in arduino that i interface with java. The arduino is connected to the computer via usb cable , I use the serial communication.
 I have two variables:

//Code in arduino
int ADelay = 1000;
int BDelay = 1000;

I want to change the value of each variable based on the input of the user using the java interface.
Is there a code that let the arduino identify that this data:

2000

Is intended to or for:

int ADelay

and this

300

is for

int BDelay

My only idea on how to achieve this is to add A or B before the number before i send to arduino

A2000
B300

And use Delimeter in arduino to split the data and use if else condition to decide where the data belong , Is there any other way ? Thanks


texts:
How can I connect this little ship to my Arduino? I can find alot of tutorials how to do it so, but all I find is 8 pins, mine includes 10 pins, and from what I could of understand from searching me myself, that there is 2 pins of VCC and 2 GRN pins.

So I would like to know how to connect this? Not necesserly Arduino, but can someone help me with the pins names at least so I can identify them.
Thanks.


texts: Arduino Mega 2560 LED is dim when powered from digital output

texts:
My circuit is a simple one, I am using an arduino atmega 2560.
One 5mm red LED connected in series with a 150 ohm resistor.
If I didn't make some kind of goof, a red LED has a voltage drop of 2 volts and operates at 20 ma.
So my calculations were, 5-2=3volts.
3V/150=20 mA. So I put a 150 ohm resistor.
My code to control it is the following:

int red = 48;

void setup() {
pinMode(OUTPUT,red);
}

void loop() {
digitalWrite(red,HIGH);
}

When I run the code the red LED is dimly lit, when connected to the 5V on the board it lights brightly.
When I measured the voltage between pin48 and ground I got 1.7 volts.
When connected directly to the 5V and GND the voltage between them is 4.95V.
Measuring a pin with nothing connected set at HIGH results in a 4.99V reading.
Is my board malfunctioning or have I missed something?


texts:
I'm trying to connect arduino uno and ev3 by using this guide (http://www.dexterindustries.com/howto/connecting-ev3-arduino/),
everything works perfectly but when i tried to use analogRead block to display data from arduino it just displays  i2c address of my arduino.


texts: Based on this question on the Adafruit forum for Nth-Light Narrow LED Flexible Strip Light (https://www.adafruit.com/product/3683) and the image below is it safe to connect from the 12v source + a wire to the Vin (orange wire) or it is better to connect to another DC barrel?


texts: SerialGSM for GSM shield without SoftwareSerial

texts:
SerialGSM is a library for simplifying GSM shields.

This is sample code for sending SMS:

#include <SerialGSM.h>
#include <SoftwareSerial.h>
SerialGSM cell(2,3);
void setup(){
 Serial.begin(9600);
 cell.begin(9600);
  cell.Verbose(true);
  cell.Boot();
  cell.FwdSMS2Serial();
  cell.Rcpt("+972123456789");
  cell.Message("hello world");
  cell.SendSMS();
}

void loop(){
  if (cell.ReceiveSMS()){
    Serial.println(cell.Message());
    cell.DeleteAllSMS();
  }

}

As you can see, he uses software serial.

I intend to use this for my school thesis, but I am using a shield, so I won't be using Software Serial.

What bothers me is this line

SerialGSM cell(2,3);

In my case, do I declare it like this?:

SerialGSM cell(0,1);

Or will there be conflicts with serial?

EDIT: In other words, how do I declare the SeralGSM object using hardware serial and not software serial?


texts: ESP8266: system_adc_read_fast() always give 1024 as output

texts:
I need to use system_adc_read_fast (uint16 *adc_addr, uint16 adc_num, uint8 adc_clk_div) to get a sampling rate close to 100ksps. And I am able to achieve that using adc_clk_div = 32.

However, when I print out the values stored in adc_addr, I always get 1024. Why is this?

I have a NodeMCU v3. I have connected an electret microphone to it. +ve terminal is connected to 3.3V through 10k; GND is connected to GND. +ve terminal is connected to A0 on NodeMCU.

simulate this circuit – Schematic created using CircuitLab

It works fine when I use system_adc_read() (except the sampling rate is then 10ksps which is not desirable).

Sketch

// Expose Espressif SDK functionality - wrapped in ifdef so that it still
// compiles on other platforms
#ifdef ESP8266
    extern "C" {
        #include "user_interface.h"
    }
#endif

ADC_MODE(ADC_TOUT);

#define num_samples 512
uint16_t adc_addr[num_samples]; // point to the address of ADC continuously fast sampling output
uint16_t adc_num = num_samples; // sampling number of ADC continuously fast sampling, range [1, 65535]
uint8_t adc_clk_div = 32; // ADC working clock = 80M/adc_clk_div, range [8, 32], the recommended value is 8

int i = 0;
unsigned long start = 0;
unsigned long total = 0;
unsigned long tim = 0;

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

void loop() {
    // put your main code here, to run repeatedly:
    #ifdef ESP8266
        // Serial.println(system_get_sdk_version());

        wifi_set_opmode(NULL_MODE);
        system_soft_wdt_stop();
        ets_intr_lock( ); //close interrupt
        noInterrupts();

        start = micros();

        // Serial.println(system_adc_read());
        system_adc_read_fast(adc_addr, adc_num, adc_clk_div);

        unsigned int tot = micros() - start;

        interrupts();
        ets_intr_unlock(); //open interrupt
        system_soft_wdt_restart();

        tim += tot;
        total += num_samples * 1000000.0 / tot;
        i++;

        for (int j=0; j<adc_num;  j++) {
            Serial.println(adc_addr[j]);
        }

        if (i == 100) {
            // Serial.print("Sampling rate: ");
            // Serial.println(total / 100);
            // Serial.print("It lasted: ");
            // Serial.println(tim / 100);

            i = 0;
            tim = 0;
            total = 0;
        }
    #endif
}


texts: How do I include a file that is not a .h, .c or .cpp file?

texts:
I am using the ADF7030 on the breakout board (not motherboard) and I am trying to interface it with an Arduino Uno. I want to load the transceivers configuration file onto the chip using SPI. To do this, I need to include the ".cfg" file but when I use the C style array (as in the datasheet - code below) it says that it can't find the file in the .ino sketch.

const unit8_t Radio_Memory_Configuration [ ] = {
     #include "Settings_ADF7030-1.cfg"
}

How could I include this file?


texts: Arduino Mega 2560 not recognized/overloaded

texts:
I pulled my Arduino set out of storage yesterday and was very upset to find that it is not working for some reason.  Before I explain the problem, let me explain the situation.

Hardware (all DFRobot):

Arduino Mega 2560

Arduino Mega 2560 4x-platform breakout board

GPIO Expansion Shield V1.0

I/O Expansion Shield V7.1

8 Channel 5V Relay Board

4 LED/Resistor set up

1 digital speaker

1 digital humidity/temperature tester

7 analog chemical air chemical testers

The whole project:

LED Portion:

Relay Portion:

Sensor Portion:

Pin Connections:

In this 4th photo, the two analog pin sets in use right in front are the ones I remove in order to gain control again.  if those are plugged in then it doesnt work.  It has nothing to do with those pins specifically, If I remove any two it works again, those ones are just easiest to remove to get it to work:

Explanation of project:

This is basically a test station, where I can hook up what ever I want and see how it works and then move onto another peripheral piece of hardware and make them interact.  I went with the 4x-platform breakout board as to maximize I/O space.  Once a project is done, I Velcro band them together as to not get them confused and move on.

Explanation of problem:

When I plugged the Arduino into my PC the first time, the lights came on the Arduino and then after about 15 seconds it powered down and the lights went off.  My PC did recognize it while it was powered up and the port option under tools in the Arduino IDE was available and I could select the port.  After the power down and problems I realized something must be up.

I considered the fact that maybe the Velcro was constricting the wires and causing them to short circuit through the rubber insulation, but couldn't find any info on that online.

After this I decided to cut the PC out of the equation and try just plugging it into the wall, 1st, via USB to 5V1A wall charger, it stayed on for a few seconds and then turned off, 2nd with a 5V2A wall charger, same scenario, 3rd via the barrel jack with the same wall chargers, with no success.

I undid all of the wire bundles to rule out a short circuit, which it did.  I then found out after much trial an error that if I removed any 2 of any analog or digital wires, the lights would stay on and it would work.

Now, with two cables removed so it did not lose power, I plugged it into my PC and am now able to program it again and see it in the port in the IDE, but as soon as I plug in another 2 analog or digital peripheral devices it will lose all power and stop working.

I also tried plugging my DFRobot Beetle micro-controller in with the same USB cable and it worked perfectly.  I also tried resetting the micro-controller, to no avail.

Conclusions so far:

A short between rubber insulation at 5v is extremely unlikely

one would think that if a mega board was designed to have so many I/O pins you could actually connect to all of them with out any problem.

Since this happened on both the PC and wall charger scenarios, and the problem seems to be associated when disconnecting any 2 sensors, the problem is most likely at the micro-controller level.

Questions:

are all the peripheral devices draining the board so much that the USB port on the PC or wall chargers cant handle it?

How do I provide enough power to the board if this is the problem?

Or is this simply faulty board?

If it is a faulty board, what causes this and how do you avoid it?

Just to clarify, looming the wires together into bundles is OK right?

Finally, any help would be really appreciated, this is the first time this has happened and it sucks.


texts: Make your own Cheap + Value Packed Arduino Starter Kit?

texts:
so I have recently started messing around with little electronics circuits and was thinking I should get an Arduino, along with some other bits and pieces, so that I can create my own little Arduino projects. I realised I was basically just creating my own Arduino starter kit. I do not want to buy a pre-made starter kit because they don't seem to contain too much value for the price.  So I created my own with the help of Ebay, here is the list of parts.

3pcs Rotary Potentiometer
$1.54

Active Buzzer Speaker
$1.59

Electronic Parts Pack kit with some resistors, switches and potentiometers
$3.67

4x4 Matrix 16 Keypad Keyboard Module
$1.22

Super super mini Arduino compatible board for use with simple projects
$3.15

4 X R130 Motor Type 130 Hobby Micro Motors 3-6V DC 0.35-0.4A 8000 RPM
$4.00

500pcs Mix 3mm Blue Red Yellow Green
$6.78

10x Mini Momentary Push Button
$3.18

UNO R3 ATmega328P Development Board With Boot Loader For Arduino GH
$4.48

400pcs 6cm Jumper Cables
$2.59

This document contains all of the links to Ebay listings
https://docs.google.com/document/d/1x8q0QxDpUQF2-as_I5olF4uv0kSW2qPRtG4mDE2o6o8/edit?usp=sharing

*All prices are in AUD

Let me know if you think there is a better option or something else I am missing


texts: Can I use string and int in Serial.println together?

texts:
I just yesterday started programming on Arduino, and I have a little problem.

I want to print "#S|SKAITYMAS|[1]#" in one line, except instead of "1" I would like to use an int value. However, this one doesn't work:

Serial.println ("#S|SKAITYMAS|[",LINENR,"]#");

Any hint or tips would be appreciated.


texts: Arduino Serial Monitor only returning Null Characters

texts:
I'm trying to simply access my HC_05 bluetooth module and conduct some AT commands through the Serial Monitor. For some reason though, it only seems to be returning Null characters, though it does some to be actually responding to the command in some way (given by the length of Null characters it returns.

So you can clearly see that the command AT and AT+NAMEdevice return different data, but they are both all NUL blocks. I am viewing the monitor in text. Changing the view to Hex or ASCII does not change results.

Code for this simple program is below:

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Wire Diagram is as here
NOTE I have used both a direct connection to the 5V and also used a Voltage Divider. Neither changes the NUL return.


texts: DC motor fan speed control with Temperature Sensor

texts:
I used this circuit schematic for the project however, when DC Motor starts to work, temperature value is increasing abnormally high. How can I solve this problem? It shows abnormal high values like 70, 85 ,101 etc.

#define TEMPERATURE A0
#define fan 3
void setup(){
Serial.begin(9600);
pinMode(fan, OUTPUT);
}

void loop(){
float temp = analogRead(TEMPERATURE);    //Read the analog pin
temp = temp * 0.48828125;   // convert output (mv) to readable celcius

Serial.print(temp);
//print the temperature status
Serial.print('\n');
delay(1000);

 if (temp<=24){
  analogWrite(fan, 51);

  delay(1000);

}
else if (temp<=26 && temp>24){
  analogWrite(fan,122);

  delay(1000);

}
 else if (temp<=30 && temp>26){
  analogWrite(fan,223);

  delay(1000);

}
else if (temp>30){
  analogWrite(fan,255);

  delay(2000);

}
}


texts: Arduino SoftwareSerial library basic example doesn't work

texts:
I come to you again because I have a problem with the Arduino SoftwareSerial library. With a basic example I fail to see results in the serial monitor.

The basic code example:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
void setup() {
  mySerial.begin(4800);
}
void loop() {
    mySerial.println("HELLO");
    delay(100);
}

I guess it should show the string "HELLO" on the serial port, but nothing appears. I have found that the baud setting is correct. The hardware is simple. Only an Arduino Uno v3 without any connected component.


texts: Using the MIDI library in my own library

texts:
Error message :

"error: invalid declarator before 'MIDI'
         MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
                                                       ^
Plusieurs bibliothèque trouvées pour "libMidi.h"
/home/due32/Arduino/libraries/MIDI/midi_Defs.h:170:31: note: in definition of macro 'MIDI_CREATE_INSTANCE'
     midi::MidiInterface<Type> Name((Type&)SerialPort);"

libMidi.h

#ifndef libMidi_h
#define libMidi_h

#include <Arduino.h>
#include <MIDI.h>

    void midiSetup();
    void pmbMIDI();

//  void MIDI_CREATE_DEFAULT_INSTANCE(); //doesn't work

#endif

libMidi.cpp

#include "libMidi.h"
#include <MIDI.h>

void midiSetup(){

//midi::MidiInterface<Type> Name((Type&)SerialPort);

        void MIDI_CREATE_DEFAULT_INSTANCE();
        void MIDI.begin(MIDI_CHANNEL_OMNI);
}

void pmbMIDI(){
    if (MIDI.getType() == 144){
        digitalWrite(13, 1);}

    if (MIDI.getType() == 128){
        digitalWrite(13, 0);}
}

Thank you by advance


texts: Hello everyone can someone help me? I tried my Arduino sound sensor but it has a problem. When I connect VCC and GND sound detect led always working but it should work only when it detects noise. Does anybody have that kind of problem if yes how did you solve it?


texts:
I'm using a SIM A9G.  When I send HTTP GET command from the serial monitor, it responds. But, it doesn't work when included in the code.
#include <SoftwareSerial.h>
SoftwareSerial myserial(8, 7); // RX: 8, TX:7

void setup()
{
//  Wire.begin(I2C_SLAVE_ADDRESS);
  Serial.begin(19200);
  myserial.begin(19200);    // 9600, 19200, 38400, 57600, 74880, 115200

//  ET.begin(details(mydata), &Wire);
  Serial.println("JSON Initializing...");
  Serial.println("GPRS Starting..........");

//  myserial.listen();
  myserial.println("AT");
  delay(500);

  myserial.println("AT+CREG=?");     //Check Network regiistration, wait a while
  delay(1000);
  ShowSerialData();

  myserial.println("AT+CCID");  //Specify the connection type
  delay(1000);
  ShowSerialData();

  myserial.println("AT+CGATT=1");
  delay(2000);
  ShowSerialData();

  myserial.println("AT+CGDCONT=1,\"IP\",\"web.gprs.mtnnigeria.net\"");//Specify the APN
  delay(2000);
  ShowSerialData();

  delay(2000);
}

void loop()
{
  myserial.println("AT+CGATT=1");
  delay(2000);
  ShowSerialData();

  myserial.println("AT+CGACT=1,1");
  delay(2000);
  ShowSerialData();

  myserial.println("AT+HTTPGET=\"https://postman-echo.com/get?foo1=bar1&foo2=bar2\"");
  delay(5000);
  ShowSerialData();

  myserial.println("AT+CCLK?");
  delay(1000);
  ShowSerialData();

  delay(3000);
}

void ShowSerialData()
{
  while (myserial.available() != 0)
  {
    Serial.write(myserial.read());
    //delay(50);
  }
}

The output at the serial monitor is the following:
+CGATT:1

OK
AT+CGACT=1,1

OK
E⸮⸮T⸮OZ⸮y:/⸮͵*⸮⸮⸮m/⸮⸮⸮⸮⸮=bar1&foo2=bar2"

+CME ERROR: 53
failure, pelase check your network or certificate!

AT+CCLK?

+CCLK: "21/02/22,18:19:43+01"

OK


texts: Why does my Arduino Nano send the wrong voltage on a digital output PIN?

texts:
Adruino nano powered by 12v through VIN pin.

Normally I expect ~12v on digital output pin, when i write HIGH to this pin, and ~0v when i write LOW. But what I have instead

digitalWrite(pin, HIGH); // I have 1.5v on pin
digitalWrite(pin, LOW);  // I have 0.5v

Algorithm is quite simple - On push button toggle output pin state.
Connections:

VIN - +12v
GND - ground
d2 - input pin (0 0, 12 - 1, button);
d3 - output pin (we change state of this pin)

Input works as expected.

simulate this circuit – Schematic created using CircuitLab


texts:
I have figured out how to make a piezo buzzer play two tones at once with analogWrite() and tone() but how would I make an actual song by playing both bass and treble, such as this one. Here is the circuit I had to do it:

and here is the code I had to do it:

int buzzer1 = 9;
int buzzer2 = 10;

void setup() {
  pinMode(buzzer1, OUTPUT);
  pinMode(buzzer2, OUTPUT);
}

void loop() {
  analogWrite(buzzer1, 100);
  tone(buzzer2, 262);
}


texts:
Below i have an example of a temperature sensor.What i need to be able to set the username an password dynamically before connecting to my home router.It would ask me for the ssid and password for example.example. Ive seen a couple of posts about this with no definitive code to show how it would work.If anyone has experience with this could they comment here please.

#include
#include
#include
#define ONE_WIRE_BUS 8
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#define SSID "[YOUR_SSID]"
#define PASS "[YOUR_PASSWORD]"
#define IP "184.106.153.149" // thingspeak.com
String GET = "GET /update?key=[THINGSPEAK_KEY]&field1=";

void setup()
{
  Serial.begin(9600);
  sensors.begin();
  Serial.println("AT");
  delay(5000);
  if(Serial.find("OK")){
    connectWiFi();
  }
}

void loop(){
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);
  tempC = DallasTemperature::toFahrenheit(tempC);
  char buffer[10];
  String tempF = dtostrf(tempC, 4, 1, buffer);
  updateTemp(tempF);
  delay(60000);
}

void updateTemp(String tenmpF){
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  Serial.println(cmd);
  delay(2000);
  if(Serial.find("Error")){
    return;
  }
  cmd = GET;
  cmd += tenmpF;
  cmd += "\r\n";
  Serial.print("AT+CIPSEND=");
  Serial.println(cmd.length());
  if(Serial.find(">")){
    Serial.print(cmd);
  }else{
    Serial.println("AT+CIPCLOSE");
  }
}

boolean connectWiFi(){
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  Serial.println(cmd);
  delay(5000);
  if(Serial.find("OK")){
    return true;
  }else{
    return false;
  }
}


texts: Any idea why my LED fails to operate with the if statement

texts:
I have tried several workarounds without success.

#include <LiquidCrystal.h>
float tempC;
int tempPin = 0;// BS E D4 D5 D6 D7
int buzzer = 4;
int LED =2;
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
unsigned char i;
void setup()
{
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("Temp        C ");
pinMode(LED, OUTPUT);
pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output
}
void loop()
{
tempC = getTemperature();
lcd.setCursor(6, 0); // Display Temperature in C
lcd.print(tempC);
delay(500);
}
float getTemperature()
{
int tempReading = analogRead(tempPin); // This is OK
double tempK = log(1000000.0 * ((1024.0 / tempReading - 1)));
//Temperature in Kelvin
tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );
return (tempK - 273.15);

if (tempC>0)
digitalWrite(LED,HIGH);
else
digitalWrite(LED, LOW);
}


texts: Communication between three NodeMCUs such that one in in AP mode, second one in AP+STA mode and the third NodeMCU in STA mode

texts:
I am able to establish a connection between first and second NodeMCU, but unable to do so for the third nodeMCU. I used the IP  address to establish connection.
Should I assign a different IP to each nodeMCU so that communication can take place?
In the code that I had written, i have taken the same IP for all three NodeMCUs, so   communication was possible between 1st nodemcu(in AP mode) and 2nd nodemcu(in STA+AP mode).
For the 3rd node mcu the IP taken was different. Can any one suggest what to do next.


texts:
I am making a home coming/leaving light for car. First I want that whenever I press the car key lock, a timer will start for 10 seconds. And if I press a button twice within 10 seconds, pin 13 will remain high for 10 seconds. If I don't press the button it returns to the void loop or condition may get false. I am working on it but I'm not getting the correct approach. I'm not able to use millis twice in this program.

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;
unsigned long previousMillis = 0;
const long interval = 5000;

void setup() {
  Serial.begin(9600);
  pinMode(8, INPUT_PULLUP);
  pinMode(13, OUTPUT);
}

void loop() {
  unsigned long currentMillis = millis();
  buttonState = digitalRead(8);
  if (buttonState != lastButtonState) {
    if (buttonPushCounter <= 2) {
      if (buttonState == LOW) {
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes: ");
        Serial.println(buttonPushCounter);
        if (buttonPushCounter % 3 == 0) {
          if (currentMillis - previousMillis > 10000) {
            digitalWrite(13, HIGH);
            previousMillis = currentMillis;
          } else {
            digitalWrite(13, LOW);
          }
        } else {
          digitalWrite(13, LOW);
        }
      } else {
        digitalWrite(13, LOW);
      }
    } else {
      buttonPushCounter = 0;
    }
    lastButtonState = buttonState;
  }
}


texts: What are the differences between an Arduino Yún and a Arduino Uno with an added Yún Shield? And is there a way to expand the storage of the Yún / Yún Shield?


texts: Power consumption in Arithmetic Operation in Arduino UNO

texts:
I would like to know how much current is consumed by multiplication operation in Arduino (ATMega328P) microcontroller. As per ATMega328p datasheet, multiplication operation takes 2 cycles. I have to now convert it to current.

Please let me know how to calculate it. Attached is ATMega328p datasheet for frequency versus current graph.


texts: NodeMCU v1.0 high power consumption in deepsleep

texts:
I am using a NodeMCU v.1.0 ESP-12 for a small project. It is powered by 3xAA batteries (4.5v) in Vin, but to reduce power consumption I need to put in in deepsleep every now and then.

Running this small sketch:

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

  // Wait for serial to initialize.
  while(!Serial) { }

  Serial.println("I'm awake.");

  Serial.println("Going into deep sleep for 20 seconds");
  ESP.deepSleep(20e6); // 20e6 is 20 seconds
}

void loop() {
}

I have measured a consumption of 8mA when it goes to deepsleep, and this is not acceptable for my purpose. In order to wake up from sleep I have connected pin GPIO16 (D0) to RST, and it works. I knew that NodeMCU should have only few µA of consumption in deepsleep. How can I fix this?


texts: Servo make partial rotation and stop working automatically

texts:
I'm using this board in my robotic arm project:
Adafruit PCA9685 16-Channel Servo Driver (
https://learn.adafruit.com/16-channel-pwm-servo-driver/using-the-adafruit-library)
I've connected all of my servo and now I'm trying to calibrating each one.
This is my configuration:

Setup
pwm = Adafruit_PWMServoDriver(0x40);
pwm.begin();
pwm.setOscillatorFrequency(27000000);
pwm.setPWMFreq(50);

Movement
pwm.setPWM(pinPosition, 0, power);

The power is mapped using map and minPulse and maxPulse based on this data structure:
ServoSettings servo0 = ServoSettings{
   0,   // pinPosition
   125,  // minPulse
   400, // maxPulse
   125  // currentPWM
};

I'm using minPulse and maxPulse for calibration and currentPWM to store data for each servo.
Data is sended through iPhone via BLE.

My servo, start rotating from 125 to ~280 and returns to back and stopped working. I need to power off my board and move the servo from its 0 position just to make movements again.
I don't understand two things:

why the rotation is not 180° but about 45°?
why after 45° servo come back home and stop working?

I suppose that is due to a wrong Adafruit library configuration but of course I'm not sure.

Using a manual loop instead of BLE data, result is the same:
moveServo is a wrapper of pwm.setPWM(pinPosition, 0, power)
  delay(1500);
  servoMgr.moveServo(0, 90);
  Serial.println("0");
  delay(1500);
  servoMgr.moveServo(0, 125);
  Serial.println("A");
  delay(1500);
  servoMgr.moveServo(0, 145);
  Serial.println("B");
  delay(1500);
  servoMgr.moveServo(0, 190);
  Serial.println("C");
  delay(1500);
  servoMgr.moveServo(0, 220);
  Serial.println("D");
  delay(1500);
  servoMgr.moveServo(0, 250);
  Serial.println("E");
  delay(1500);
  servoMgr.moveServo(0, 280); // <<<--- here servo come back home and die.
  Serial.println("F");
  delay(1500);
  servoMgr.moveServo(0, 300);
  Serial.println("G");

The Adafruit board is powered with an external 9V battery.
Arduino is powered with USB cable.
Can be something related to voltage?
What's wrong with the library configuration?
The board now have only 1 servo attached, just for test.
These are the used servo: https://www.amazon.it/dp/B07KD6NVPM
thanks for your suggestions.


texts: My car only moves when it is plugged directly into both my pc and battery pack?

texts:
i built a car that works with four motors,one motor driver(specifically the l293d),the arduino and the battery pack with four AA-Batteries. The motors work fine though, but they only work when it is connected to the laptop and the battery pack.I've also removed the METAL insulation from the copper wire and now it is copper.Sadly i have also connected the two poles together and there was some lightning but no fire thankfully(by accident of course).if anyone else had the same issues and fixed them please contact me.
Thank you very much stranger.


texts:
I want to make a very small 7-hour timer circuit that can turn on a relay after 7 hours. I am trying to make the first prototype with an Arduino Nano but I can't understand how to program it for such purpose. So please help me out.

Once I make a prototype in Arduino then I was thinking to make a small one  using an ATtiny13. Can I use an ATtiny13 for such purpose?


texts: Can a MEMS accelerometer sensor be used as a shock sensor?

texts:
I am trying to make an IOT project- SMART DOOR where I have used a serve motor and NodeMcu and for adding further functionality I have been thinking of adding a theft detection feature where whenever a large force is applied on the lock an alarm starts beeping and for that I don't have a shock sensor but I do have MEMS accelerometer sensor(MPU6050 Accelerometer and Gyroscope).
So can I use it to add this functionality?
If yes, can I get a little guide on what configuration and sensitivity I should use?

THANK YOU!


texts:
I am trying to upload the Blink example from the Arduino IDE to a ESP8266-01 module using an Arduino Uno as serial programmer.
Now, the upload is successful but, upon restart (and disconnecting GPIO0 from GND), nothing happens. I have tried with different example sketches but it seems code was not uploaded.

My Board manager configuration

Board: Generic ESP8266 Module
Flash mode: QIO
Flash frequency: 40 MHz
CPU frequency: 80 MHz
Flash size: 1M (128K SPIFFS)
Debug port: Serial
Debug level: none
Reset method: ck (tried nodemcu too without success)
Upload speed: 115200
USB port

As an addition, here's what I get from the ESP01 through the Arduino IDE Serial monitor:

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
e:
 ets Jan  8 2013,rst cause:3, boot mode:(3,7)

ets_main.c

and here's the IDE console window output:

sptool.py v1.3
Connecting..........
Auto-detected Flash size: 8m
Running Cesanta flasher stub...
Flash params set to 0x0020
Writing 229376 @ 0x0... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x0 in 39.0 seconds (47.0 kbit/s)...
Writing 229376 @ 0x10000... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x10000 in 39.0 seconds (47.0 kbit/s)...
Leaving...

The sketch I am using

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}


texts:
I am using NodeMCU dev board with ESP8266 WIFI.

Every time I try to connect to my local broker it returns this error:

failed, rc=-2 try again in 5 seconds

I am using Ubuntu 18.04, my local brokers are Mosquitto and EQMTT. I tried both of them through pubsubclient library and it doesn't connect. Using MQTT Box works connecting to my local brokers. Connecting to my WiFi also works. When I connect to a MQTT broker using pubsubclient e.g. mqtt://test.mosquitto.org:1883/ it works. It just doesn't seem to work with local broker. This is the code:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "mywifi";
const char* password = "password";
const char* mqtt_server = "127.0.0.1";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup() {
  pinMode(D7, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(D7, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(D7, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(1000);
    }
  }
}
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}

Note: The brokers are running, I can even connect it through MQTT Box (attached picture).


texts: Arduino add two spi slaves that has no slave select pin

texts:
I am working on a project where Arduino is communicating with two devices using SPI. Unfortunately, these two devices has no ss(slave select) pin to communicate with each one separately.

How Can I solve this issue?

Sensor example

Thanks


texts:
I'm working on a driver for an SPI device that returns some data (device status) while the command byte is still being written.  Is there a way to read this status data using standard Arduino APIs or do I need to bit-bang to access it?
Here's what the SPI signals look like:

The 6 bits in red are the ones I'm interested in reading.

For context, the device in question is a Microchip MCP3561 ADC (MCP3X6X series).  It has a bug (erratum 2) where the new-data-ready flag (/DR_STATUS) is not always set correctly.  Part of the work-around involves reading the status bits mentioned above.


texts: Help understanding SoftwareSerial recv() and PCINT

texts:
In the SoftwareSerial library, I see the beginning of recv() as follows

void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {

This comment seems to be testing for if the pin change was from low to high, or high to low.  If you are using inverse logic - where the line is held high, and start bits are low - then a call to rx_pin_read() should return 0.

This doesn't seem correct.  In inverse logic the line is held high and a drop indicates a start bit.

Is the SoftwareSerial library ignoring the start bit and relying on some kind of return to zero break between the start bit and any subsequent bits?

It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.


texts:
I recently read this post about setting up Eclipse for Arduino.  I Build the test project with no erros, but when I go to upload my test project it just hangs at 5%, with no error messages.

If I unplug the arduino-uno it cancels the upload, so I know it can see the arduino board. It is just not uploading. Does anyone have any ideas as to what is wrong?

I don't know whats changed, but now it doesn't hang i just get a message after trying to upload:

  avrdude: stk500_recv(): programmer is not responding


texts: Sharing a Digital Pin / What to do when two components need a specific Digital Pin?

texts:
I am new to the world of Arduino and picked up an Uno R3. I have run into a situation where I have two components that specifically need digital pin 11, 12, 13 as specified by the libraries used to interact with them.

Each component also uses other pins that were able to be specified as different with the libraries but for those 3 the libraries say I cannot change them. What do you do in a situation like this? Is it somehow possible for two components to use the same pins? Any help is appreciated.

The two libraries I am trying to use are https://github.com/nRF24/RF24 (Wifi Receiver & Transmitter using component nrf24l01+) and https://github.com/steigeia/RFID_UNID_LOGGER/blob/master/libraries/AddicoreRFID/AddicoreRFID.h (RFID Reader/Writer using component RC522).


texts:
Probably something stupid, but I can't figure out how to work with these large numbers, then cast the result (which will be small) to an integer. I keep getting negative numbers, which I think means I'm overflowing somewhere.

int freq = 440;
int len = 256;
long timer = 2000000.0 / (freq * len);
int roundedTimer = int(timer);

I should get 18, but I'm getting -108...


texts: Connecting two pressure sensors with one uno

texts:
I'm trying to connect two BMP180s to an arduino uno by using a multiplexer.

Here is the code that a guy has written before:
I imported SFE_BMP180 library but didn't do anything with the "typedef.h" thing.

I'm getting "Data does not name a type" error at the line 9.
How can  I solve this problem?

     #include <SFE_BMP180.h>
    #include <Wire.h>
    #include "typedef.h"

    #define SELECT_PIN 9
    #define ALTITUDE 510.0

#define P1_ACTIVE digitalWrite(SELECT_PIN,HIGH); //delay(10);
#define P2_ACTIVE digitalWrite(SELECT_PIN,LOW);  //delay(10);

SFE_BMP180 bmp1,bmp2;
boolean readSensors(Data *data1, Data *data2);

Data newData(char id)
{
  Data d ;
  d._id = id ;
  return d ;
}
void setup()
{
    boolean failed = false ;
    pinMode(SELECT_PIN, OUTPUT);

    Serial.begin(9600);

    P1_ACTIVE

    if(bmp1.begin()){
        Serial.println("BMP #1 init success.");
    }
    else
          failed = true ;

    P2_ACTIVE
    if(bmp2.begin()){
          Serial.println("BMP #2 init success.");
    }
    else
        failed = true ;

    if(failed){
        Serial.println("Error in BMP180 init.");
        while (1);
    }
}

void loop()
{
  Data d1 = newData('1');
  Data d2 = newData('2');

  boolean read = readSensors(&d1,&d2);

  if(read){
          /* print the value to serial terminal */
...


texts: Controlling an analog potentiometer using an Arduino

texts: I want to be able to control an analog potentiometer. I'd like to be able to go from the minimum range to the maximum range possibly using an Arduino and a motor/servo. I want to be able to control vintage equipment, so the knobs on the pot must still work. I want to be able to rotate both by hand and by sending  a (MIDI) signal.How would I go about doing this?


texts:
I bought a waterproof temperature sensor from Ebay, I am fairly new to this and not sure what I need or need to do in order to get the sensor to output the current temperature to the serial monitor.

Does anyone have any information on where I can get some information on how to wire this? I have looked at various videos online but they are all for a dallas temp sensor and use the dallas library.

http://www.ebay.co.uk/itm/181393039374?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1439.l2649


texts: Control Air Pump Depending on Pressure Sensor

texts:
I am working with an Arduino Mega, a 12V micro air pump, and a MP3V5050 air pressure sensor. The sensor outputs an analog voltage depending on the pressure reading in an inflatable member. I'd like to turn on the micro air pump when the pressure is too low and turn off the pump when the pressure exceeds a determined threshold (exact pressure ranges are currently undetermined).

I have been looking for similar tutorials but this is my first experience working with Arduinos and most existing tutorials are either sensing or pump control, not both. I only have minor coding experience with MATLAB, so any help with this is appreciated. Thank you!


texts: Please help me combine the two codes for DHT11 and SW-420 Vibration sensor for arduino in one program

texts:
The following is the code used for DHT11 Temperature and Humidity sensor:

#include <LiquidCrystal.h>
LiquidCrystal lcd(4, 5, 0, 1, 2, 3);
byte degree_symbol[8] =
              {
                0b00111,
                0b00101,
                0b00111,
                0b00000,
                0b00000,
                0b00000,
                0b00000,
                0b00000
              };
int gate=11;
volatile unsigned long duration=0;
unsigned char i[5];
unsigned int j[40];
unsigned char value=0;
unsigned answer=0;
int z=0;
int b=1;
void setup()
{

lcd.begin(16, 2);
 lcd.print("Temp = ");
 lcd.setCursor(0,1);
 lcd.print("Humidity = ");
 lcd.createChar(1, degree_symbol);
 lcd.setCursor(9,0);
 lcd.write(1);
 lcd.print("C");
 lcd.setCursor(13,1);
 lcd.print("%");
}

void loop()
{

 delay(1000);
 while(1)
 {
  delay(1000);
  pinMode(gate,OUTPUT);
  digitalWrite(gate,LOW);
  delay(20);
  digitalWrite(gate,HIGH);
  pinMode(gate,INPUT_PULLUP);//by default it will become high due to internal pull up
 // delayMicroseconds(40);

  duration=pulseIn(gate, LOW);
  if(duration <= 84 && duration >= 72)
  {
      while(1)
      {
        duration=pulseIn(gate, HIGH);

        if(duration <= 26 && duration >= 20){
        value=0;}

        else if(duration <= 74 && duration >= 65){
        value=1;}

        else if(z==40){
        break;}

        i[z/8]|=value<<(7- (z%8));
        j[z]=value;
        z++;
      }
    }
answer=i[0]+i[1]+i[2]+i[3];

if(answer==i[4] && answer!=0)
{
lcd.setCursor(7,0);
lcd.print(i[2]);
lcd.setCursor(11,1);
lcd.print(i[0]);
}

z=0;
i[0]=i[1]=i[2]=i[3]=i[4]=0;
 }
}

The following is the code for SW-420 Sensor:

int LED_Pin = 13;
int vibr_Pin =3;

void setup(){
  pinMode(LED_Pin, OUTPUT);
  pinMode(vibr_Pin, INPUT); //set vibr_Pin input for measurment
  Serial.begin(9600); //init serial 9600
 // Serial.println("----------------------Vibration demo------------------------");
}
void loop(){
  long measurement =TP_init();
  delay(50);
 // Serial.print("measurment = ");
  Serial.println(measurement);
  if (measurement > 1000){
    digitalWrite(LED_Pin, HIGH);
  }
  else{
    digitalWrite(LED_Pin, LOW);
  }
}

long TP_init(){
  delay(10);
  long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

Assuming the DHT11 Pin configuration remains unchanged and you can change the pin configurations for SW-420 vibration sensor, please give me a combined code for the two sensors to display results in one program. Thanks a lot.


texts: Digital output from one nano to digital input of another.

texts:
Can I connect the digital out of one arduino to a digital input of another? To detect a high/low state...
One powered in one room on USB. The other in another room separate psu (connecting the grounds).
I know I can use tx/rx serial. But if the other way would work, less programming and 1 wire less..


texts: Why does void loop() stop after some samples?

texts:
I am not getting any compile time error. After some samples of data void loop() stops executing. Please let know what the problem is. Below is my code.

Thanks and regards
Thippeswamy

#include<SPI.h>
float amplitude=1.5;
int freq1=20; int freq2=12;
int k=20;float A= amplitude*k;
int Fs=10550; float sine[5000]; float Fs1=3000;
int i=0;int reg1=1; int reg2=0;
int sample1=Fs/freq1; float sample2=Fs1/freq2;

void setup() {
  int SS=10;
  pinMode(SS, OUTPUT);
  SPI.begin();
}

void data(int reg, int data) {
  digitalWrite(SS,LOW);
  SPI.transfer(reg);
  SPI.transfer(data);
  digitalWrite(SS,HIGH);
}

void loop() {
  for(int j=0;j<sample1||i<sample2||i>=sample2);j++) {
    float s=A*sin((2*3.14*freq1*j)/Fs);
    sine[j]=s+190;
    data(reg1,sine[j]);
    if(i<=sample2) {
      float s=A*sin((2*3.14*freq2*i)/Fs1);
      sine[i]=s+190;
      data(reg2,sine[i]);
      i++;
    } else if(i>sample2) {
      float s=A*sin((2*3.14*freq2*i)/Fs1);
      sine[i]=s+190;
      data(reg2,sine[i]);
      i++;
    }
  }
}


texts: As I mention in the title, that when I am trying to upload the code of WebServer to the Ethernet Shield it shows me an error messages. Please if any one can help me to fix it, and here is the screenshot of the errors:


texts:
I followed the instructions of this post: Storing an array of function pointers.
To show my problem I shorted my code extremely but the problem is still there.

My classes are defined as followes:

class MyBaseClass
{
public:
  MyBaseClass(String functionName);
  String functionName();
private:
  String _functionName;
};

class MyDerivedClassA : public MyBaseClass
{
public:
  MyDerivedClassA(String functionName);
};

class MyDerivedClassB : public MyBaseClass
{
public:
  MyDerivedClassB(String functionName);
};

MyBaseClass::MyBaseClass(String functionName) {
  _functionName = functionName;
}

String MyBaseClass::functionName(){
  return _functionName;
}

MyDerivedClassA::MyDerivedClassA(String functionName) : MyBaseClass(functionName) {}

MyDerivedClassB::MyDerivedClassB(String functionName) : MyBaseClass(functionName) {}

The test method is this:

void test(){
  MyBaseClass *_elements[1000];
  int _elementCount = 0;

  for (int i = 0; i < 2; i++){
    if (i == 0){
      MyDerivedClassA tmp("MyDerivedClassA");

      _elements[_elementCount] = (MyBaseClass *)&tmp;
      Serial.println( _elements[_elementCount]->functionName() );

    } else if (i == 1){
      MyDerivedClassB tmp("MyDerivedClassB");

      _elements[_elementCount] = (MyBaseClass *)&tmp;
      Serial.println( _elements[_elementCount]->functionName() );

    }

    Serial.println( _elements[_elementCount]->functionName() );

    _elementCount++;
  }

  Serial.println("count: " + String(_elementCount));
  for (int i = 0; i < _elementCount; i++) {
    Serial.println("loop: " + String(i));
    Serial.println( _elements[i]->functionName() );
  }
}

When the code is running I get the following at the serial monitor:

MyDerivedClassA

MyDerivedClassB

count: 2
loop: 0

loop: 1

I dont understand, why the first call of "_elements[_elementCount]->functionName()" inside the first loop returns the correct value and the second only an empty string. Inside the second loop it again returns an empty string. I think it's the same problem like inside the first loop.

And there is the problem, that my NodeMCU crashes if the code is executed.

This is the output while it carshes:

Soft WDT reset

ctx: cont
sp: 3ffffd20 end: 3fffffd0 offset: 01b0

>>>stack>>>
...
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,7)

 ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset

Where is my problem?


texts: How do I make a character array scanner properly?

texts:
I start with this:

char delay_chars[10];

then I have a stream of incoming characters that I need to assign like this:

['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e']

I can do that, but then more characters come in so I need it like this:

[' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e', ' ']
['l', 'o', 'v', 'e', ' ', 'p', 'i', 'e', ' ', 'a']
['o', 'v', 'e', ' ', 'p', 'i', 'e', ' ', 'a', 'n']
['v', 'e', ' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd']
['e', ' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd', ' ']
[' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'c']
['p', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'c', 'a']
['i', 'e', ' ', 'a', 'n', 'd', ' ', 'c', 'a', 'k']
['e', ' ', 'a', 'n', 'd', ' ', 'c', 'a', 'k', 'e']

You get the idea. I don't know how I can remove the first character of a char array (like I do with a String, remove(0, 1)) and I don't know how to add a new element at the end.

If I had to guess, I'd make a loop that will reassign the index of each character one step back or something like that but I'm not sure if that's how I should do it.


texts:
I am using an ESP32 module for bluetooth connection and scaning wifi network. But I cannot format the json using arduinojson library in the way I want.

void scanWifiNetworks() {
  //creating json
  DynamicJsonDocument jsonDoc(1024);
  char jsonBuffer[512];
  JsonObject wifiJsonObject = jsonDoc.createNestedObject("wifiList");
  wifiJsonObject["ssid"];
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0) {
    Serial.println("no networks found");
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
//      Serial.print(i + 1);
//      Serial.print(": ");
//      Serial.print(WiFi.SSID(i));
//      Serial.print(" (");
//      Serial.print(WiFi.RSSI(i));
//      Serial.print(")");
//      Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");

      wifiJsonObject["ssid"] = WiFi.SSID(i);
      serializeJsonPretty(jsonDoc, SerialBT);
      serializeJsonPretty(jsonDoc, Serial);
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(60000);
}

The output is like this

scan start
scan done
5 networks found
{
  "wifiList": {
    "ssid": "quark"
  }
}{
  "wifiList": {
    "ssid": "Airtel_Zerotouch"
  }
}{
  "wifiList": {
    "ssid": "NETGEAR77"
  }
}{
  "wifiList": {
    "ssid": "Itobuz-technologies"
  }
}{
  "wifiList": {
    "ssid": "Nokia 6.1"
  }
}

what I want is something like that

{
      "wifiList": {
        "ssid1": "quark1",
         "ssid2": "quark2"
     }
}

I know I am looping in a wrong way but could not figure it out. if possible please pointing out the right direction will help a lot.


texts: Nano 33 IoT rescue from the dead: No USB. No upload mode

texts:
First of all: my board used to work fine.

Now my Nano 33 IoT turns ON (green light) when connected to USB on Mac but:

doesn't enter in upload mode after pressing twice on board button.
doesn't shows up in any serial port: nor /dev/cu.usbmodem14*01, neither /dev/tty.usbmodem14*01

For reasons too long to explain, I want to connect via ANY pins to the SAMD21 and force the burning of a new bootloader.

Is that possible in any way? Any idea is welcome!

Tx


texts: Read from analog then cast not showing the correct value

texts:
I'm trying to read the analog value of the light sensor and print its percentage but for unknown reasons I'm getting negative values when I'm printing the value.

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

void loop() {

  // Let's say 1002 is the analogValue
  int analogValue = (int) analogRead(0);

  // get the percentage
  int value = 100 * analogValue / 1023;

  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
  Serial.println(analogValue); // print the analog value 0...1023
  Serial.println(100 * analogValue); // just for test
  Serial.println(value); // The percentage
  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");

  delay(500);
}

I don't know what's going in background, but I'm getting negative values when I try to print the percentage:

~~~~~~~~~~~~~~~~~~~~~~~~~
1002
-30772
-30
~~~~~~~~~~~~~~~~~~~~~~~~~


texts: Chinese CH340 Arduino Uno - Burning stand allone chip

texts:
I followed regular tutorial and I was able to burn boot-loader on my standalone ATM328 chip, but because I'm using this CH340 UNO and example is with regular UNO, I can't just remove the chip from there (CH340 UNO) and upload the code directly to my new standalone chip trough that board.

So what I tried was to use my FTDI cable, so I hooked up GND, RX, TX and VCC for my breadboard from there, but when I tried to upload a sketch I keep getting that message that programmer is not responding.

So I was wondering, is there a way to use this Chinese board to upload sketch to my new chip without de-soldering the chip from that board as option one.

As option two what I'm doing wrong with FTDI cable and why I'm not able to upload sketch directly like that? I saw some comments related to some auto-reset that needs to be implemented but I'm not following that part, not sure what I need to hookup extra for that...

UPDATE

Here's how my board look like:

Update 2:

OK, everything works great now! I just needed one pull-up resistor for reset pin.

Thanks everyone!


texts: About maximum length of matrix can be use for matrix invertsion on atmega32

texts:
what is the maximum length for matrix can be used for matrix inversion on atmega32,for example,can we implement matrix inversion for 15x15 matrix on atmega32? And if  it can be done on atmega32..does this will make the atmega32 to be slower?
I want to implement kalamn filter 15 states for euler angles estimation...the data of the matrix will be floating point..


texts:
I wonder if in Arduino you can modify the computer eg create a text file inside the computer using Arduino. Is there any way you can do this or something like that?

Because you can use the library #include <stdio.h>, which is a C++ language library to handle file on the computer.

In Arduino maybe you can create files on the computer using pointers or a library? Because using the library "Keyboard.h" you can handle the computer. The Keyboard library can interact with the computer by typing on the computer

I'm in doubt, I need your knowledge.


texts:
I'm trying to build a led equalizer using arduino and I want to light up with the frequencies.

And I need a little help on how I should do it cause Im a beginner.

Should I use pulsein() or analogin pin to measure the freqeuencies?

The input will be an audio cable.


texts: TCP connection CPU usage, multiple signals?

texts:
I'm connecting a client (java program) to an arduino (server). What I want to know is, how high the CPU usage is, and what to do if there are no clients that are trying to connect to arduino? Should I make a delay?

My code looks like this:

EthernetClient client = server.available();

if(client){
    Serial.println("Connected");
    server.write("Hello\n");

    //check if client is still connected
    while (client.connected()){
        Serial.println("Still there");
        delay(2000);
       //check if client received any data
       if(client.available()){
           //read message from client
     }
  }
} else {
     Serial.println("Nope");
     server.write("Hello\n");
     ???????????? delay(2000); ??????????????
}

Thank you for your help.


texts: Can the Arduino Eclipse plugin v2.2 be used with Arduino 1.5.8?

texts:
It keeps giving me this warning:

  You are using a version of the Arduino IDE that is newer than available at the release of this plugin.`

Does this means I need to use a night build?


texts: It is possible to program Linino to send HTTP requests and then use the returned values in sketch?

texts:
I am new to using Arduino Yun and I would like to know if it is possible to run a command from the Arduino sketch in order to make (probably, through the Bridge Library) Linino to execute a HTTP Request to a remote server. Then I would like to know if it is possible to use the returned values in that Arduino sketch.

In other words, I would like to delegate the task of retrieving values from the web to the Linux side and the usage of the retrieved data to the sketch.

If it is possible, how to do that?


texts: Having trouble assigning colour to my neopixels

texts:
Hi I was wondering if someone is able to help me! I am currently trying to get a strip of 10 neopixels to change colour. I want to be able to code a random neopixel in the strip to change to either red, blue, green and yellow consecutively after 2 seconds. I am relatively new to Arduino so I'm still learning. I have been using the code below and it does everything that I want it to but I would like to set the colour so they're not as randomised. I found this code online.

#include <Adafruit_NeoPixel.h>

#define PIN 6
#define LED_COUNT 50
Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_RGB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop()
{
  randomPixelColor(100);

}

void randomPixelColor(int wait)
{
  int i= random(strip.numPixels());

  uint32_t c = random(2147483647); // I have no idea what this crazy number does.
  strip.setPixelColor(i, c);
  strip.show();
  delay(1000);

}    // end void randomPixelColor()

I don't even know if this is the right code to be using! Hopefully someone can help me cause I'm so confused.


texts: Arduino bug when "myFile = SD.open" is inside loop()

texts:
My Arduino resets / bugs each time I put myFile = SD.open in loop().

In setup() it works fine.

I have a 20*4 LCD and an RTC connected to I2C, an SD card reader connected to SPI, and a fingerprint sensor.

Here is my code:

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <SD.h>
#include <DS3231.h>;

LiquidCrystal_I2C lcd(0x3f,20,4);
DS3231  rtc(SDA, SCL);
SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
Sd2Card card;
SdVolume volume;
SdFile root;

int etat = 0;
int getFingerprintIDez();
const int chipSelect = 10;
SDFile myFile;

void setup() {
  lcd.init();
  lcd.backlight();
  rtc.begin();
  finger.begin(57600);
  SD.begin();

  // Reglage Heure
  //rtc.setDOW(TUESDAY); // Set Day-of-Week to SUNDAY
  //rtc.setTime(10, 57, 0); // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(24, 11, 2016);   // Set the date to January 1st, 2014
  if (finger.verifyPassword()) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Initialise");
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Deconnecte");
  }
  delay(2000);
  if (SD.exists("data.csv")) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("data.csv OK.");
    delay (1000);
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Creating data.csv...");
    myFile = SD.open("data.csv", FILE_WRITE);
    myFile.close();
    delay (1000);
  }
}

void loop() {
  if (etat == 0) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Put Finger");
    getFingerprintIDez();
  }
  if  (etat == 1) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("ID #");
    lcd.setCursor(4,0);
    lcd.print(finger.fingerID);
//  myFile = SD.open("data.csv", FILE_WRITE);
//  myFile.print(rtc.getDateStr(1));
//  myFile.print("\t");
//  myFile.print(rtc.getTimeStr(1));
//  myFile.print("\t");
//  myFile.println(finger.fingerID);
//  myFile.close();
    lcd.setCursor(0,2);
    lcd.print("Loged");
    etat = 0;
  }
  delay(1000);
}

int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Found ID #");
  lcd.setCursor(14,0);
  lcd.print(finger.fingerID);
  etat = 1;
  return finger.fingerID;
  delay(1000);
}

Each time I uncomment lines using SD, the Arduino resets at the end of the loop.

What is the problem?