texts:
I have a project to make where I have to read tags out of 5 RFID Readers and when every tag is in correct reader to open a relay. The schematic is the same with Annaane's with the difference I have 5 Readers, so I didn't make one.
I also have made the board that i have attached so I can connect all the common pins together (MISO, MOSI, SCK, RESET, 3.3V and GND)
The SDA SS pins are connected directly to pins 3-7 of Arduino.
My code works just fine when powering arduino through my Laptop's USB port but since it have to be installed somewhere I tried the following ways to power it:

USB coming from a Xiaomi 5v Phone Charger to Arduino's USB port
USB coming from this to Arduino's USB Port. It is being powered from a 12v 1amp power supply from and old router.
The 12v 1amp power supply from and old router.
L7805CV and it's suggested circuit from the datasheet

My problem is that none of these ways seem to work properly. What I mean is that I cant get readings from the Readers as it should do. I have an LED which lights up when it read a tag but at these cases it only lights up only on some of the readers. The strange part is that when I am charging my laptop and powering arduino through its usb port it doesnt work either.
Any help please?


texts:
I try to send pairs of numbers over the serial port from a linux pc to the arduino. By now I did so always by piecing together the ASCII chars from the serial line and using Serial.read(). Now I need this same thing to run at 100-200Hz, and it turns out, that the Arduino does not receive all the data (even at 1Hz).

As turned out, my problem was in another portion of the code and all below code works perfectly as is!

How do I make sure, that every char (or better even byte without ASCII encoding) is received? I am aware, that each connection has errors, but this is a systematical error! I guess, that the bytes are lost during the processing within the main loop, or because of other callbacks I use (got some ISR running). I am not looking for error detection, but rather a concise way of reading the serial line, without loosing 70% of the data validity.

If important: the pairs i need to send are unsigned, 1 byte and another one with 2 bytes. The values are in the range of [0;7] and [1000;2000]. Thanks for any advice. Disclaimer, I read a lot, including this, but most questions go into detail about the packaging format, whereas I am concerned about the reading method.

Code I use at the moment:

// read numbers from the char representation!
// on the serial connection
// each DIGIT is sent separately

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
uint8_t channel; // holding the number of the channel to modify
uint16_t signal; // ppm signal length in us (1000-2000)

void setup() {
  Serial.begin(115200);
  inputString.reserve(200);

  pinMode(9,OUTPUT); // fixed pin 9 for PPM output
}

void loop() {
  if (stringComplete) {
    channel = uint8_t(inputString[0])-48;
    signal = 0;
    for (uint8_t n=1; n<5; n++) {
      signal = (signal*10) + uint8_t(inputString[n])-48;
    }
    Serial.print(F("ch: ")); Serial.print(channel);
    Serial.print(F(" signal: ")); Serial.print(signal);
    Serial.print(F("\n"));
    //PROCESS Data
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    // if the incoming character is a
    // newline (10) or carriage return (13)
    // set a flag for a complete transmission
    if (inChar == 10 | inChar == 13) {
      stringComplete = true;
    }
  }
}

Another version I tried, without strings is:

// channel and pulse-length
uint16_t numbers[2] = {0, 0}; // channel,value
uint8_t buf[5];

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

void loop() {
  if (serial_input(numbers,buf)) {
    numbers[0] = buf[0]-48;
    numbers[1] = (buf[1]-48)*10+(buf[2]-48);
    Serial.print(F("channel: ")); Serial.println(numbers[0]);
    Serial.print(F(" signal: ")); Serial.println(numbers[1]);
    // Do Stuff
  }
}

uint8_t serial_input(uint16_t* num, uint8_t* buf) {
  uint8_t newData = 0;
  uint8_t k = 0;
  num[0] = 0; num[1] = 0;
  while(Serial.available()) {
    delayMicroseconds(2100);
    char ser = Serial.read();
    if (isDigit(ser)) {
      buf[k] = uint8_t(ser);
      k++;
      newData = 1;
    } else {break;}
  }
  return newData;
}

Another try inspired by an answer here, where I send "3 1500\n" over the serial line:

void serialEvent() {
  if (!newdata) {
    channel = Serial.parseInt();
    signal = Serial.parseInt();
    newdata = true;
  }
}

Turns out all of those methods work (more or less elegantly), but having a "delay" within an ISR isn't such a good idea - even intermediately...


texts: Set avrdude transfer baud rate in Arduino IDE

texts:
I just got an Arduino nano (from arduino.cc, not a knock-off), and have issues uploading sketches. It refuses to upload, with the error message "programmer is not responding".

Some searching led to an incorrect transfer baud rate. Indeed, the IDE (1.8.5) output before uploading displays "overriding baud rate: 57600", and the command line has a -b57600 argument. By copying this command in a terminal and removing this parameter, the upload works. It also works with -b115200. All other values I tried do not work.

Is there a way to configure the IDE to use the correct baud rate ? I know I could use the command line, but that's not very practical, I would prefer to keep the Integrated part of the IDE :).


texts:
I have an issue communicating with ESP8266 via Arduino Uno's serial ports.

I can connect to it using
python -m serial.tools.miniterm /dev/ttyUSB0 115200
command but when trying to send an AT command, it looks like this:

�tC�

ERROR
�v[�
ERROR
at

OK

So, sometimes I'm able to properly send a command, but usually what I type turns to gibberish. I've tried other baud values, but only 115200 works.

I'm powering Arduino via USB from my laptop. I've seen some mentions that this behavior may be caused by low voltage but unfortunately, I'm currently unable to verify it whether that's a case here.

My schematic looks like this:

I'm new to this, so if there is any crucial information I've missed, then please let me know and I'll do my best to provide it.


texts:
I'm defining a variable as integer and want to use thati

int specLength = 17;
int spec[specLength-1];

When I do this, I get the following error message:

 TestProgram:34: error: array bound is not an integer constant before  ']' token
 int spec[specLength-1];

But when I set it up as

int specLength = 17;
int spec[16];

it all works fine.

What is the magic here?

Many thanks


texts: Unable to compile SimpleTimer code - Exit status 1

texts:
I downloaded the SimpleTimer library from the Arduino's library manager and navigated to Arduino Playground website for some sample code for testing - SimpleTimer - Arduino Playground. After copying the following code into the Arduino IDE:

#include <SimpleTimer.h>

// the timer object
SimpleTimer timer;

// a function to be executed periodically
void repeatMe() {
    Serial.print("Uptime (s): ");
    Serial.println(millis() / 1000);
}

void setup() {
    Serial.begin(9600);
    timer.setInterval(1000, repeatMe);
}

void loop() {
    timer.run();
}

I receive the following error:

exit status 1
no matching function for call to 'SimpleTimer::setInterval(int, void (&)())'

Please help me out here as I am doing everything according to the instructions given in the arduino playground page of SimpleTimer.


texts: How do I write and read internal EEPROM?

texts:
I am working on an Arduino Mega 2560. I want to read and write the internal EEPROM.

Can I use EEPROM.get()/EEPROM.put()?

I want to store 3 things in EEPROM:

Boolean status.
String password: length 5 digits.
String Mobile number: length 10 digits.


texts: I2C code working on Mega 2560 but not on Uno and nano

texts:
I have recently purchased this Heart rate sensor and was trying to make it work. I used this MAX30100 library I found on Github. For some reason when I use any of the given examples, they seem to work well when I use a Mega2560 I have but not on the Uno or Nano. Does this have to do with the processor? I don't think so because the README on Github mentions that they tested it on an Uno. But if it is so, how could I change the code to make it work with the Uno and nano?

Example Code I used:

// This example can be used to test connectivity and operation of the sensor
// check the README file on the repo's root for a troubleshooting guide in casem
// any of the tests running fail

#include <Wire.h>
#include "MAX30100.h"

MAX30100 sensor;

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

    Serial.print("Initializing MAX30100..");

    if (!sensor.begin()) {
        Serial.print("FAILED: ");

        uint8_t partId = sensor.getPartId();
        if (partId == 0xff) {
            Serial.println("I2C error");
        } else {
            Serial.print("wrong part ID 0x");
            Serial.print(partId, HEX);
            Serial.print(" (expected: 0x");
            Serial.println(EXPECTED_PART_ID, HEX);
        }
        // Stop here
        for(;;);
    } else {
        Serial.println("Success");
    }

    Serial.print("Enabling HR/SPO2 mode..");
    sensor.setMode(MAX30100_MODE_SPO2_HR);
    Serial.println("done.");

    Serial.print("Configuring LEDs biases to 50mA..");
    sensor.setLedsCurrent(MAX30100_LED_CURR_50MA, MAX30100_LED_CURR_50MA);
    Serial.println("done.");

    delay(1000);

    Serial.print("Lowering the current to 7.6mA..");
    sensor.setLedsCurrent(MAX30100_LED_CURR_7_6MA, MAX30100_LED_CURR_7_6MA);
    Serial.println("done.");

    delay(1000);

    Serial.print("Shutting down..");
    sensor.shutdown();
    Serial.println("done.");

    delay(1000);

    Serial.print("Resuming normal operation..");
    sensor.resume();
    delay(500);
    Serial.println("done.");

    uint32_t tsTempSampStart = millis();
    Serial.print("Sampling die temperature..");
    sensor.startTemperatureSampling();
    while(!sensor.isTemperatureReady()) {
        if (millis() - tsTempSampStart > 1000) {
            Serial.println("ERROR: timeout");
            // Stop here
            for(;;);
        }
    }

    float temperature = sensor.retrieveTemperature();
    Serial.print("done, temp=");
    Serial.print(temperature);
    Serial.println("C");

    if (temperature < 5) {
        Serial.println("WARNING: Temperature probe reported an odd value");
    } else {
        Serial.println("All test pass.");
    }

    Serial.println();
    Serial.println("Press any key to go into sampling loop mode");
    while (!Serial.available());

    sensor.resetFifo();
}

void loop()
{
    uint16_t ir, red;

    sensor.update();

    while (sensor.getRawValues(&ir, &red)) {
        Serial.print("IR=");
        Serial.print(ir);
        Serial.print(" RED=");
        Serial.println(red);
    }
}


texts: Managing timer intervals using millis at random intervals

texts:
I am doing a project which needs to meet the following specifications.

  On receiving an SMS arduino will start switching 1st relay on after some
  time duration(say 30 Seconds) relay 1 will be turned off and it will now turn on 2nd relay for (say 20seconds) so on 1>2>3>4.

The problem im facing is managing the time intervals between the switching process,i did think of using millis() i.e (currentMillis-previousMillisx>Intervalx) as in blinkWithoutDelay ,how ever this will work only once as i dont not know when will the next SMS come to the system ,if the user decides to send the message after 1hour currentMillis-previousMillisx will always return true so i cannot keep the motor on for (Say 30 seconds) and same will happen with all 4 cases.

If there is any alternative logic for this problem please suggest me or can i just add RTC for my project to manage time easily

Thank You


texts:
I am working on esp8266 module with arduino uno board.  This is my program.

#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different
   Serial.print("START");
  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

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

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

  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
     pinNumber += (esp8266.read()-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    Serial.println(esp8266.print(command)); // send the read character to the esp8266

    long int time = millis();
    while( (time+timeout) > millis())
    {

      while(esp8266.available())
      {
        Serial.print("Coming");

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

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

    return response;
}

the problem is  i am not getting any output from esp module but arduino is transmitting the data.  power supply for esp is given by 3.3v regulator (LD3.3)feeding 12v from arduino power supply adapter  to regulator input .
TX esp to rx arduino
arduino tx to esp rx by voltage divider (R1=1k and R2=1.8k)
esp gnd  to arduino gnd
chpd and esp vin are 3.3v from regulator
Can anyone tell me where the problem is ?


texts: I would like to know the purpose of the LEDs on top of the Arduino WiFi Shield: L9/Link/Error/Data (left in the picture). What do they indicate?


texts:
I've received my ESP8266-01 and playing with it I discovered that with a baudrate of 74880 I can get the boot modes and `hy version, etc:
 ets Jan  8 2013,rst cause:1, boot mode:(3,0)

load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79

2nd boot version : 1.5
  SPI Speed      : 40MHz
  SPI Mode       : DIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 249
rf[112] : 00
rf[113] : 00
rf[114] : 01

SDK ver: 1.5.4.1(39cb9a32) compiled @ Jul  1 2016 20:04:35
phy ver: 972, pp ver: 10.1

With this baudrate I'm not able to check the AT commands. Then, when I switch to a baudrate of 115200 I am able to communicate with the ESP:

Ai-Thinker Technology Co. Ltd.
ready
AT
OK
AT+CWL
ERROR
AT+CWJAP?
No AP
OK
AT+CWLAP?
ERROR
AT+CWLAP
+CWLAP:(4,"bbox2-7f0d",-88,"00:1 ",1,-46,0)
+CWLAP:(0,"PROXIMUS_FON",-94,"06: ec:6b",1,-47,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-88,"0a: :ec:6b",1,-44,0)
+CWLAP:(3,"WiFi-2.4-BB3D-ext",-51,"00: 9a:38",1,-12,0)
+CWLAP:(3,"NGUYEN",-79,"e0:b ",11,-2,0)
+CWLAP:(0,"PROXIMUS_FON",-81,"42:6 ",11,0,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-79,"42 ",11,0,0)
+CWLAP:(4,"WiFi-2.4-6858",-75,"4 e",11,1,0)
+CWLAP:(0,"PROXIMUS_FON",-89," ",11,-6,0)
OK

How is that possible that it has two different baudrates?

Thanks in advance,


texts: NodeMCU - use flash button as input in loop()

texts:
I couldn't find a proper answer on the net so I came here as a last resort.
So I want to use the FLASH button as an input in the loop() method.

Is there a way the check if it's pressed or not?


texts: Using Arduino Yún to send data through Ethernet

texts:
I'm still new to Arduino Yún and I can't find any tutorials or examples on making the Yún send data through Ethernet, which will then be showed on a web server.

I've seen other tutorials but they use Uno with an Ethernet shield.  Is it the same with the Yún too?

How can I send data through Ethernet using Yún?


texts: data streaming using Bluetooth + RFduino

texts:
I am trying to send ECG data using RFduino. I am using two RFduino modules. The transmitter module is using the device code while the receiver is using the host code. I have common baud rate between the two modules which is 250k. I have an issue with the first data that comes to the receiver . Always a question mark is displayed in the beginning as shown in the figure below:

I do not want this question mark to appear at the beginning because it is making issues in the analysis side.

Codes:

device:

/*
This sketch demonstrates how to send structured data from a Device
to a Host in a Gazell network.

Written by (VLorz) Victor Lorenzo.

You are free to use this code.
*/

#include <RFduinoGZLL.h>
#include "myStruct.h"

/* This instance will be sent over GZLL */
static my_struct_t  theStruct;

/* And this variable is for timing */
static long PrevTime;

/* It would be nice to know if the host received the packet */
static bool   Acked;
static int    AckedCount;

void setup()
{
  // Initialize the structure to a known state;
  //theStruct.OneByte = 1;
  //theStruct.OneDWord = 0x02030405;
  theStruct.ECG = 0x0000;
  //theStruct.Count = 0;
  Serial.begin(250000);
  //pinMode(3, INPUT); // Setup for leads off detection LO +
  //pinMode(2, INPUT); // Setup for leads off detection LO -
  Serial.println("CLEARDATA"); //clears up

  Serial.println("RESETTIMER"); //resets timer to 0
  // start the GZLL stack;
  Serial.print( F("GZLL init...") );
  Serial.println( RFduinoGZLL.begin( DEVICE0 ) );

  Serial.println( F("Running") );

  /* Force the first xmit */
  PrevTime = millis() - 1001;
  Acked = false;
}

void loop()
{
  long  Now;

  Now = millis();

  if (4 <= Now - PrevTime) {
    Acked = false;

    // This is simply for making something change;
    theStruct.Count++;
    theStruct.ECG  = analogRead(2);
    // So we send the struct to the host;
    RFduinoGZLL.sendToHost( (char*)&theStruct, sizeof(theStruct) );

    PrevTime = Now;
  }

  if (Acked) {
    Acked = false;
    //Serial.print( "Ack received for Count = " );
    //Serial.println( AckedCount );
    Serial.println(theStruct.ECG );
  }
}

void RFduinoGZLL_onReceive(device_t device, int rssi, char *data, int len)
{
  // What we expect here is the host sending the value in the Count field from
  // the structure we have sent;
  if (len == 1)
    AckedCount = (uint8_t)*data;
  else
    AckedCount = -1;

  Acked = true;
}

The host:

/*
This sketch demonstrates how to send structured data from a Device
to a Host in a Gazell network.

Written by (VLorz) Victor Lorenzo.
You are free to use this code.
*/

#include <RFduinoGZLL.h>
#include "myStruct.h"

/* This instance will be filled with data received over GZLL */
static my_struct_t  theReceivedStruct;

/* It would be nice to know if the host received the packet */
static bool   DataReady;

void setup()
{
  Serial.flush();
  Serial.begin(250000);

  // start the GZLL stack;
 // Serial.print( F("GZLL init...") );
  Serial.println( RFduinoGZLL.begin( HOST ) );
  //Serial.println( F("Running") );

  DataReady = false;
}

void loop()
{
  if (DataReady) {
    //Serial.println( "Data received!!!" );
    //Serial.print( F("OneWord=") );
    Serial.println( theReceivedStruct.ECG, DEC );
    //Serial.print( F("Count=") );
    //Serial.println( theReceivedStruct.Count );
   // Serial.println( "" );
    DataReady = false;
  }
}

void RFduinoGZLL_onReceive(device_t device, int rssi, char *data, int len)
{
  //
  // IMPORTANT!!! This function runs under interrupt context!!!
  //

  if (DataReady) {
    // Do not overwrite our buffer;
    return;
  }

  if (len != sizeof(theReceivedStruct)) {
    // Ignore packets with wrong length!!!
    return;
  }

  // Copy the data to our structure buffer;
  for (char* lpDest = (char*)&theReceivedStruct; len > 0; len--) {
    *lpDest = *data;
    lpDest++;
    data++;
  }

  // ...and signal the application the data is ready
  DataReady = true;

  RFduinoGZLL.sendToDevice( device, theReceivedStruct.Count );
}


texts: How to debug Arduino using Atmel studio?

texts: I have an Arduino Yun board and an Atmel ICE programmer/debugger. There are 6 pins on the Arduino Yun to connect to Atmel ICE for programming only, but I can't find the pins for debugging. Anyway to do so? Which pins on the Arduino should I connect to Atmel ICE?


texts: How can one reset Arduino Nano from NodeMCU?

texts: If one connects the RESET pin on an Arduino Nano to a digital pin on a NodeMCU, will the NodeMCU be able to reset the Nano by setting said pin to LOW?


texts:
I'm learning this note about timer's api on Arduino Due. Interrupt can be attached with the next function:
void tc_enable_interrupt(
       Tc * p_tc,
       uint32_t ul_channel,
       uint32_t ul_sources)

Where the input parameter ul_sources can be one or more of the following:

TC_IER_COVFS Enables the Counter Overflow Interrupt
TC_IER_LOVRS Enables the Load Overrun Interrupt
TC_IER_CPAS  Enables the RA Compare Interrupt
TC_IER_CPBS  Enables the RB Compare Interrupt
TC_IER_CPCS  Enables the RC Compare Interrupt
TC_IER_LDRAS Enables the RA Load Interrupt
TC_IER_LDRBS Enables the RB Load Interrupt
TC_IER_ETRGS Enables the External Trigger Interrupt

I'm more like mobile developer and I don't understand what does all this interrupt types mean.


texts:
I am working on a power meter project with ZMPT101B and SCT013. I want to see the phase difference between voltage and current in the serial plotter but the results are like this? Why do you think the current reading is not a sine like a voltage wave?]
2]2


texts: Trouble reading LM35 with long (?) Ethernet connection

texts:
I have a quick question to ask.
I have an Arduino Uno reading 4 temperature sensors (LM35) in 4 different rooms. What happens is that the two nearest rooms give stable values, while the two further ones give very unstable measurements (the temperature keeps floating +-30C around the real values.)

I have connected all the sensors with Ethernet cables with the longest one being about 8-10m.

Is this problem due to noise picked up along the line? There are no strong electromagnetic sources along the way.
I have also measured the voltage values on Arduino end with a multimeter: the values are all stable (and correct) and do not reflect the behaviour detected by Arduino.

Also, I have tried to substitute the LM35 in the farthest room with a photoresistor (the one in the starter kit) and this time the values read by Arduino are perfectly stable. I know that the LM35 works because I have tested it on a breadboard.

Can someone give my some help? Any idea is greatly appreciated.

Edit: I am adding a sketch, although it is a very basic setup:
The only difference with the real layout is that there is also a Ethernet shield.


texts: Problems reading I2C sensor when using a Xbee module

texts:
I'm developing a project where I can control a RC boat with GPS and a magnetometer. How ever, I was developing everything connected to my computer and worked pretty well. When I was going to make some test with a battery and a couple of Xbee's (PC and "Arduino"), the magnetometer signal was not updating. So, I read the first value and continued to transmit the same value (thing that never happened on computer). Has someone had the same issue before? How can I solve this? Oh, one thing. The GPS and magnetometer comes in the same module, and I'm having no problems with GPS coordinates. And even if I power de MCU with my computer and transmitting with the Xbee's it doesn't work either. Seems like a communication problem.

Hardware used:

GPS Module + Compass

ATmega1284P

UPDATE:

I want to share also the code I'm using for the I2C reading.

#include <Wire.h> //I2C Arduino Library
#define address 0x1E //0011110b, I2C 7bit address of HMC5883

void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  Wire.endTransmission();
}

 void loop(){

  int x,y,z; //triple axis data

  //Tell the HMC5883L where to begin reading data
  Wire.beginTransmission(address);
  Wire.send(0x03); //select register 3, X MSB register
  Wire.endTransmission();

 //Read data from each axis, 2 registers per axis
  Wire.requestFrom(address, 6);
  if(6<=Wire.available()){
    x = Wire.receive()<<8; //X msb
    x |= Wire.receive(); //X lsb
    z = Wire.receive()<<8; //Z msb
    z |= Wire.receive(); //Z lsb
    y = Wire.receive()<<8; //Y msb
    y |= Wire.receive(); //Y lsb
  }

  //Print out values of each axis
  Serial.print("x: ");
  Serial.print(x);
  Serial.print("  y: ");
  Serial.print(y);
  Serial.print("  z: ");
  Serial.println(z);

}


texts: What is a cheap way to interface a USB keyboard to an Arduino Uno?

texts:
What is the cheapest way to interface a USB 2.0 keyboard to an Arduino Uno?

The keyboard does not support PS/2 emulation (interfacing a PS/2 keyboard to Arduino is easy). So this means the Arduino will read the USB keyboard's keystrokes - whatever their speed of input is.

If it can be solved using an IC then DIP is preferred as it quicker to work  with for soldering and pluggin into breadboard.


texts:
I have previously connected 5V 10A relay switches to my Arduino.

But for my new project I need to use a 5V 30A relay switch with my Arduino.

In 10A relay switches, we make connection with Arduino using GND, VCC and IN.

But for 30A switches, there are DC+, DC-, IN.

My question is that, how do I connect my Arduino to the relay using these pins?


texts: How do I use 2 ultrasonic sensors to control a 5v motor?

texts:
I've hooked up two ultrasonic sensors to my breadboard and I also got a 5v motor installed. I also got the diode installed and the usual set up. I can easily control the motor with one sensor.

But what I'm trying to do is I want the motor to run at let's say 100 once I start it up:

The first sensor should be used to slowly slow down the motor when an object is placed in front of it
The second sensor should be used to slowly speed up the motor when an object is placed in front of it

I do not want the speed to return to 100 once the object is removed. It should remain at the same speed according to which sensor was used. (Tell me if I have to clarify anything in the comments)

Code

int motorPin = 9;
int trigPin = 13;
int echoPin = 12;
int trigPin2 = 5;
int echoPin2 = 4;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(motorPin, OUTPUT);
}

void loop() {
  int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (1000);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance < 20) {  // Distance from sensor
    analogWrite (motorPin, 50);
  } else {
    int duration, distance;
    digitalWrite (trigPin2, HIGH);
    delayMicroseconds (1000);
    digitalWrite (trigPin2, LOW);
    duration = pulseIn (echoPin2, HIGH);
    distance = (duration/2) / 29.1;
    if (distance > 20) {  // Distance from sensor
      analogWrite (motorPin, 150);
    }
    if  (distance > 20) {  // Distance from sensor
      Serial.println("Out of range");
    } else {
      Serial.print(distance);
     Serial.println(" cm");
    }
    delay(500);
  }
}


texts: Is it possible to transmit using an NRF24L01+ without an Arduino?

texts:
I have two NRF24L01+ modules which are transceivers, but for my project I would like to send a very simple signal from one of these modules to the be read by the other.

That would've been very simple if I had an Arduino on each side but due to power consumption constraints as well as size, cost and practicality, the transmitting side won't have one. Would it still be possible to do this?

To clarify, the message itself is not important and can be set in stone, it will never change. I really just want to detect on the receiving side (which will have an Arduino) that the transmitter is in fact transmitting. Transmission will be triggered by a push-button.

Ideally I would have a way of identifying my particular transmitter from others on similar frequencies but I am not too precious about that.


texts: Error: Cannot find module 'serialport'. node.js, Arduino Yun

texts: I carefully followed Andy Sigler's tutorial on how to setup node.js on Arduino Yun. But I'm getting this error "Cannot find module 'serialport'". my node.js file is in mnt/sda1/arduino/node folder. and I have installed node-serialport successfully through ssh. Kindly helpc


texts: Play sound on top of background music using arduino uno tmrpcm library

texts: We designed a big piano with 15 buttons on it. Every button has a proximity sensor. Whenever users interact with the sensor a specific sound plays for that button. My code is working fine for this purpose but now I want to add background music. Our piano button sound should play on top of that background music. I am using tmrpcm library, and I already added a bg music but when I interact with the sensor, bg music stops and starts from the beginning right after the piano button sound stops. Is there a way to play a sound without interrupting a bg music. Any help will be appreciated.


texts: Working or functionality Serial.begin(9600)

texts:
In recent practice, I found out some new things.

Serial.begin(9600);

What is mean of this line of code?

Why here, we always write 9600?

And can we write manually number means instead of 9600 let's say 10000?


texts: Read an integer using Serial.read() then read a string using Serial.readStringUntil(End-Char)

texts:
I have a sketch as follows:
void loop()
    char End_Char = ‘\n’;
    if (Serial.available()) {
        aInt = Serial.read();
    }
    switch (aInt) {
    case 1:
        // does a task that is triggered by a number
        // I get correct responses if aInt=1
        break;
    case 2:
        bString = Serial.readStringUntil(End_Char);
        Serial.print(bString);
        // The sketch freezes and doesn’t do anything if I enter 2 but restarts through case 1 if I enter 1 when the sketch is seemingly frozen
        break;
    Default:
        break;
    } // end of switch
} // end of loop

I have tried re-ordering the case statements, putting in delays at various points to give time to read the string, changed the Serial.setTimeout to 100 and 2000 at various points to give time to read the string. However, the sketch fails to read the string.
This code works:
char end_char = '\n';
String texto;

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

void loop() {
    if (Serial.available()) {
        texto = Serial.readStringUntil(end_char);
        Serial.println(texto);
    }
}

I’m using an Arduino UNO, HC-06 and an Android app.
Any ideas?


texts:
When I want to write a literal string in Python, I use r before the string (or @ in C#):

in [1]: print r'\no esca\pe ch\ara\cters'
out [1]: \no esca\pe ch\ara\cters

In straight c++ I can use R, but in the Arduino IDE, this throws the following error:

Serial.begin(9600);
Serial.println(R"\no esca\pe ch\ara\cters");

<output> invalid character '\'in raw string delimiter

So how do I do the same in Arduino c++?


texts: Multiple buttons activating different methods for an LED strip

texts:
I am trying to use different buttons to activate different methods for an LED strip. However, when one button is pressed after another has been pressed, I want it to interrupt the first buttons method and begin the second. For example: one button sends a rainbow pattern through the LED strip when pressed, however, while it is cycling through the rainbow, the second button is pressed which sends a white cycle through the LED strip. There will be 24 buttons total. I have gotten this to work with 2 buttons but am having trouble getting it to work for a third. The code is below:

     void loop(){

       if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
           stopCycle();
           theaterChaseRainbow(50);
       }
       if (digitalRead(inPin(2)) == HIGH){
           stopCycle();
           theaterChase(strip.Color(127, 127, 127), 50); // White
       }
       if (digitalRead(inPin(3)) == HIGH){
           stopCycle();
           rainbowCycle(0);
       }

     }

     //Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<100; j++) {  //do 100 cycles of chasing
    if (digitalRead (inPin(1)) == LOW) { //checks that other button(s) have not been pressed
      if (digitalRead (inPin(3) == LOW)){
      for (int q=0; q < 3; q++) {
        for (int i=0; i < strip.numPixels(); i=i+3) {
          strip.setPixelColor(i+q, c);    //turn every third pixel on
        }
        strip.show();

        delay(wait);

        for (int i=0; i < strip.numPixels(); i=i+3) {
          strip.setPixelColor(i+q, 0);        //turn every third pixel off
        }
      }
    }
    }
  }
}

void rainbow(uint8_t wait) {
  int i, j;

  for (j=0; j < 384; j++) {
   if (digitalRead (inPin(2)) == LOW) { // 3 cycles of all 384 colors in the wheel
    if (digitalRead (inPin(3) == LOW)){
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel( (i + j) % 384));
    }
    strip.show();   // write all the pixels out
    delay(wait);
   }
   }
  }
}

uint32_t Wheel(uint16_t WheelPos)
{
  byte r, g, b;
  switch(WheelPos / 128)
  {
    case 0:
      r = 127 - WheelPos % 128;   //Red down
      g = WheelPos % 128;      // Green up
      b = 0;                  //blue off
      break;
    case 1:
      g = 127 - WheelPos % 128;  //green down
      b = WheelPos % 128;      //blue up
      r = 0;                  //red off
      break;
    case 2:
      b = 127 - WheelPos % 128;  //blue down
      r = WheelPos % 128;      //red up
      g = 0;                  //green off
      break;
  }
  return(strip.Color(r,g,b));
}

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for (j=0; j < 384 * 5; j++) {     // 5 cycles of all 384 colors in the wheel
    if (inPin(1) == LOW) {
      if (inPin(2) == LOW) {
    for (i=0; i < strip.numPixels(); i++) {
      // tricky math! we use each pixel as a fraction of the full 384-color wheel
      // (thats the i / strip.numPixels() part)
      // Then add in j which makes the colors go around per pixel
      // the % 384 is to make the wheel cycle around
      strip.setPixelColor(i, Wheel( ((i * 384 / strip.numPixels()) + j) % 384) );
    }
    strip.show();   // write all the pixels out
    delay(wait);

      }
    }
  }
}

void stopCycle(){
    int i;
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0);
    }
    strip.show();   // write all the pixels out
}


texts: DFROBOT I2C 16x2 Arduino LCD Display Module I2C communication interface

texts: What is the proper connection to the I2C communication interface (e.g., JST Jumper 4 Wire Assembly) of the DFROBOT I2C 16x2 Arduino LCD Display Module (SKU:DFR0063)? I wish to connect 4 wires assembly directly to it.


texts: How to implement elapsed millis as the timer for my motor spinning time?

texts:
I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.

I have tried it and to no avail, I did not get the result in wanted. Yes, the motor spin according to the speed that I desired, however, it does not spin according to the time I wanted. It kept on spinning non-stop till I have to disconnect the power supply.

So, my question is, how do I implement the elapsed millis as my timer for my spinning motor?
please, guys, help me with this... Just guide me through and give me guidance.

This is my code that I have tried using elapsed millis. Any suggestion is welcome.

#include <elapsedMillis.h>
#include <Keypad.h>
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address
elapsedMillis timeElapsed;

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] =
{
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4)
byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3)
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{

  Serial.begin(9600);
  lcd.begin(20,4);
  myservo.attach(11);

   lcd.setCursor(0,0);
  lcd.print("S=");
  lcd.setCursor(0,1);
  lcd.print("T=");
  lcd.setCursor(0,2);
  lcd.print("S=");
  lcd.setCursor(0,3);
  lcd.print("T=");
  lcd.setCursor(10,0);
  lcd.print("S=");
  lcd.setCursor(10,1);
  lcd.print("T=");
  lcd.setCursor(10,2);
  lcd.print("RPM");

}

 void loop()

{

  int stage1speed = getTheNumber();
  lcd.setCursor(2,0);
  lcd.print(stage1speed);
  lcd.print("sv");
  int stage1time = getTheNumber();
  lcd.setCursor(2,1);
  lcd.print(stage1time);
  lcd.print("sec");

  int stage2speed = getTheNumber();
  lcd.setCursor(2,2);
  lcd.print(stage2speed);
  lcd.print("sv");
  int stage2time = getTheNumber();
  lcd.setCursor(2,3);
  lcd.print(stage2time);
   lcd.print("sec");

  int stage3speed = getTheNumber();
  lcd.setCursor(12,0);
  lcd.print(stage3speed);
  lcd.print("sv");
  int stage3time = getTheNumber();
  lcd.setCursor(12,1);
  lcd.print(stage3time);
  lcd.print("sec");

   if ( stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage3speed > 0
        && stage3time > 0 )

   {

    if(timeElapsed <= 1000*stage1time)

    {

     myservo.write(stage1speed);

     }

    if(timeElapsed <= 1000*stage2time)

    {

     myservo.write(stage2speed);

     }

    if(timeElapsed <= 1000*stage3time)

    {

     myservo.write(stage3speed);

     }
  }

}

int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
           int value = atoi(buffer);  // Convert to an integer
            break;
        }

    }
    return atoi(buffer);
    }


texts: Can I automatically loop inside a library?

texts:
I want to write a little library;
the unlibrarized functionality does:

checking in every loop-cycle some inputs,
doing some calculations with it
and finally setting a boolean to either true or false.

How do I periodically check the inputs inside the library?
I know that I could add a function-call  to the library in the loop()-function. But I would prefer to just check the boolean in the loop.

Is there a way, to instantiate a class and start an periodically function by doing so? And if, how does this constant checking affect/coexist with my 'normal' loop()-function?


texts: How to separate a specific frequency signal from a summation of a few signals?

texts:
I want to calculate THD. SO how do I isolate the fundamental frequency from a signal with harmonics?
I have a signal V which is a sum of V1, V2 and V3. V1=A1sin(w1t+phi1), V2=A2sin(w2t+phi2) and V3=A3sin(w3t+phi3). I want to find out the magnitude/amplitude of a known frequency w1 in the signal. How do I proceed? Should I use the FFT library? If yes then how?


texts:
How to get a pwm pin value that is in pinMode OUTPUT?

How to get a digital OUTPUT PIN value:

#define pin 3

void setup()
{
  pinMode(pin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    delay(1000);
    digitalWrite(pin, HIGH);
    Serial.println(bitRead(PORTD,pin));
    delay(1000);
    digitalWrite(pin, LOW);
    Serial.println(bitRead(PORTD,pin));
}

For testing reasons, I want to get PWM output pin value.

Incorrect sketch:

#define pin 3

void setup()
{
  pinMode(pin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    delay(1000);
    analogWrite(pin, 100);
    Serial.println(pulseIn(pin, HIGH)); // value of the PWM output pin
}

This sketch was created for example only.
I don't know PWM value because PWM value will be generating dynamically.
Could you explain how to get a PWM output pin value, please?


texts: Posting TinyGPS++ co-ordinates as paramaters with GPRS

texts:
I'm able to view my co-ords on the Serial Monitor using Serial.println(gps.location.lat(), 6);

I believe the data type returned by gps.location.lat() is double. I need to pass this value to a webservice with AT commands over GPRS.

double latitude = gps.location.lat()

Later in my code I execute AT commands to begin HTTP POST. I would like to know how to pass these double values in my paramaters.

gsm.println("AT+HTTPPARA=\"URL\",\"http://webservice/service1\"");
 gsm.println("AT+HTTPDATA=192,10000");
 gsm.println("latitude=" + latitude); < This is not allowed.

How can I pass this parameter to my web service.


texts:
I am using a JIC 139 UV Sensor (datasheet) with an Arduino Mega 2560 and should be reading smooth curves as I bring a UV source to towards the sensor. Instead, my curves are increasing and oscillating. How can I remove the oscillations and what is the cause of these oscillations?

Code:

float mapfloat(long x, long in_min, long in_max, long out_min, long out_max)
{
    return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + out_min;
}

int averageAnalogRead(int pinToRead)
{
    byte numberOfReadings = 8;
    unsigned int runningValue = 0;

    for(int x = 0 ; x < numberOfReadings ; x++)
        runningValue += analogRead(pinToRead);
    runningValue /= numberOfReadings;

    delay(100);

    return(runningValue);
}

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

void loop() {

   float pinRead0 = averageAnalogRead(0);
   float pVolt0 = pinRead0 / 1024.0 * 5.0;

   // In mW/m^2
   Serial.println(pVolt0);
   //  Serial.println(mapfloat(pVolt0, 0.0, 5.0, 0.0, 15.0));

   delay(100);
}

`

Here is a sample screenshot from the Serial Plotter at 3 different distances from the UV Source:

Would post cicuit but don't have enough reputation. Will post as response.
edit: I added a very large capacitor(3300 uf) between the output pin and ground which seemed to smooth the values a little bit but the noise still exists

edit: The x-axis is number of readings and the y-axis is voltage(0-5v) calculated from analogRead()


texts: How to load Atmega328p 8mhz board using board manager

texts: I need to load the Atmega328p 8kHz board definition using the board manager and can not find a way.  Any help will be appreciated.


texts: Daisy Chaining USB Communication over Arduino Due

texts:
I have two Arduino Due boards. I would like to connect one to my computer through the programming port as USB Serial so that I can send it commands, but I would like it to also be able to communicate to a second Arduino Due as the host on the native USB port.

I see in the manual that it has drivers for acting as a host to USB Mice and Keyboards, but is having it load appropriate drivers for communicating with another Due doable? I've done plenty with the USB ports, but never as a host so I'm not really sure how to start.

The goal is to have one "master" Due connected to the computer that controls a complicated piece of equipment with a lot of supporting electronics, and a second "peripheral" Due that acts as an interface for the user. The master would accept commands either from the computer, or from the peripheral. Reason is that the peripheral has to have fast interrupts to handle rotary encoders and the like (the "master" Due is quite busy so those interrupts can be troublesome) and be physically located in a different place.


texts: Why using static volatile for variables and only static for arrays in TWI library?

texts:
I want to know why to declare variables with static volatile and arrays with only static in TWI library?

For example;

static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_masterBufferIndex;
static volatile uint8_t twi_masterBufferLength;


texts:
Lets Say That I Have a  routine like:

I have written PHP codes for the free domain that will:

Wait for request like url/control?ToDo="someMethod",parm=Something (posting some password for security)
and will change the database values for ToDo and parms as the request sayed
Wait for request like url/veiw (posting some password for security) and will send the values of sensors that is stored in the database
Wait for request like url/esp?Doin="someMethod",sens1=Something,sens2= ..... and will change the database values for doin and sensors as the request said
Wait for request like url/check and will send the values of ToDo and parms that is stored in the database

The problem in the code of ESP or node that they need IP to connect
the IP that I know is free domain provider's not for my link

I guess I'm missing some knowledge in servers (in english too but it's off the topic XD)  and IP things

Any one can help with a well documented method or API?

Edit:

There Were 2 main problems -:

1- I Need to know more about HTTP requests , How they look like and what should be in Headers

2- After I have build a good ones and Tried the problem was in my connection with free domain server I've checked to find out that the server is down so I moved To a reliable Server And , It worked .

I guess that's it for now ,
Thanks too you All


texts: Is it possible to program a few Arduinos at the same time?

texts:
I have 10 Arduino Pro Minis and one Arduino Uno. Via breadboard, if I connect Pro Minis in parallel, can I program all of them at same time?

Is it possible?


texts: How to serve multiple connections with an ESP8266 and an Adruino?

texts:
I want to make a server using an ESP8266 (12e) and an Arduino Nano.
I have got everything hooked and I created a minimal "Hello World" example, based on a number of samples found on the web, which is working fine... as long as the ESP does not receive multiple requests simultaneously.

I am using SoftwareSerial on pins 8 and 9 of my Arduino Nano.

As long as I send one request at the time, things work fine.
If I use two browsers and send two requests with little interval, things go wrong, and that figures: the sendData() method just reads from the serial connection. It will consume the new request while waiting for an "OK" from the initial request...

Is there any sample code or library (for ESP + Arduino (nano)) that can handle correctly multiple concurrent connections?

Thanks

My code:

/*
  Software serial multple serial test
 */
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(8, 9); // RX, TX

void setup() {

  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different : 115200

  Serial.println("Setup...");

  /*
  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+GMR\r\n",1000,DEBUG); // get version
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
  */

  sendData("AT+RST\r\n", 2000,DEBUG);
  sendData("AT+GMR\r\n", 1000, DEBUG);

  sendData("AT+CWMODE=1\r\n",1000,DEBUG); // configure as station
  sendData("AT+CWJAP=\"******\",\"*******\"\r\n", 6000, DEBUG);
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Setup ready.");
}

//WIRE RESET TO HIGH!!?

void loop() { // run over and over

if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000);

     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     String webpage = "
Hello World!
";

     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+= connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,250,DEBUG);
    }
  }

}

String sendData(String command, const int timeout, boolean debug)
{
    String response = "?";
    int pos = -5;

    Serial.println("--------------");
    Serial.println(" sending "+command);

    esp8266.print(command); // send the read character to the esp8266

    long int _timeout = timeout + millis();

    while( (_timeout) > millis())
    {
      while(esp8266.available())
      {
        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
        pos+=1;
        if(pos>=0 && response.substring(pos) == "\r\nOK\r\n"){
          //WE GOT OK -> stop waiting
          _timeout=0;
        }
      }
    }

    if(debug)
    {
      Serial.println(" response: "+response);
    }

    return response;
}


texts:
Last week I purchased a couple of Trinkets from Adafruit (5v micro-USB). The first thing I did was solder the headers to one of them. I did the whole setup process w/ the Arduino IDE and didn't have any issues, until I actually tried uploading the "Blink" example.

When I plug in the Trinket, I get the pulsing red light, but when I try to upload during that, I get:

avrdude: error: usbtiny_send: Input/output error (expected 64, got -5)
avrdude: verification error, first mismatch at byte 0x0004
         0x1d != 0x36
avrdude: verification error; content mismatch

avrdude: error: usbtiny_transmit: Input/output error

Then, if I press the reset button, I can't get it to "pulse" again. The red light just dimly turns on and stays constant.

I tested the other Trinket I ordered (that has not been soldered yet) and it works perfectly fine.

So, did I somehow screw up something when soldering the headers? Or do I have a faulty Trinket?

For reference, here's the trinket in question...


texts: Piezo buzzer with PWM on arduino uno with atmega328p in C on registers + analogRead on registers

texts:
I have a little project at the university where I have to use the timers to generate a pwm signal and get it into a piezo buzzer when something else turns over a certain value by using the registers, the thing is that we have worked on some other microcontrollers so I don't really know the libraries for arduino uno with atmega328p and I would require some help on that. Also I have to use the registers instead of the function analogRead() that is reading from a temperature sensor.

Having the following code that works for my setup:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Digital pins to which you connect the LCD
const int inPin = 0;
const int buzzer=9;// A0 is the sensor
void setup()
{
  pinMode(buzzer,OUTPUT); // DDRA=0b00000001;
  lcd.begin(16,2);
}
void loop()
{
  int value = analogRead(inPin); // read the value from the sensor <= to be written on registers
  lcd.setCursor(0,1);
  float millivolts = (value / 1024.0) * 5;
  float celsius = (millivolts-0.5)*100;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(celsius);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print((celsius * 9)/5 + 32); //turning the celsius into fahrehait
  lcd.print("F");
  delay(1000);
  if(celsius>30.0){tone(buzzer,1000);delay(1000);noTone(buzzer);delay(1000);} //<= on registers
}


texts: I want to make a keyboard type panel, which will only have 7 buttons and two knobs, and connect it arduino to program it with functions, he heard that he needed the Keyboard library. but it is not available with arduino uno, which is what I work with, he heard about what I should do a keyboard mapping, it would help me explain to lay a foundation and carry out the project that I want "please do not leave me with the doubt". first of all, Thanks.


texts: How many I2C lines does the Arduino Due have?

texts:
According to the Arduino pin Mapping

20  PB12    SDA 3   6
21  PB13    SCL 3   6
70  PA17    SDA1    3   6
71  PA18    SCL2    15  9

The first one seems pretty obvious, the second one though is confusing. They have different labels. I also do not see other SDA or SCL in the table. So is this a typo?


texts: multiple definition of local variable in linking

texts:
I am trying to make my own library and it uses some local variables with the same name as some variables in ino. Compiler complains about it. I stripped it to (nonsence but simple) example

mylib.h:

#ifndef MYLIB_H
#define MYLIB_H
int doit();
#endif

mylib.cpp:

#include "mylib.h"
int value;
int doit(){
    return value++;
}

example.ino:

#include "mylib.h"
int value;
void setup(){
    value=3;
    pinMode(13,OUTPUT);

}
void loop() {
    digitalWrite(13,(value==doit()) );
}

compiling:

$ make
/usr/bin/avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p example.o mylib.o .lib/arduino.a -lm -o example.elf
mylib.o:(.bss.value+0x0): multiple definition of `value'
example.o:(.bss.value+0x0): first defined here
collect2: error: ld returned 1 exit status
/home/gilhad/GIT/HW/Arduino/minipro//../Arduino.mk:436: recipe for target 'example.elf' failed
make: *** [example.elf] Error 1

I am not usint the value in the .h file, so why it collides with similary named variable from another module?

Should not be it private to the module until exposed via .h file?


texts:
I have this application where I want to send commands from the PC to an Arduino, remotely, and receive an answer back.

The hardware configuration I'm using to achieve that is the following:

PC <--> Arduino with an Xbee <--> Another Arduino with another Xbee

It's just half-duplex communication. Everything seems easy, but there is a problem.

Each Arduino has an Xbee Shield with an Xbee module connected to it.
Reading the documentation of the ArduinoXbeeShield, an excerpt caught my eye:

"With the jumpers in the Xbee position (i.e. on the two pins towards theinterior of the board), the DOUT pin of the Xbee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI chip - data sent from the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the Xbee module. The microcontroller, however, will only be able to receive data from the Xbee module, not over USB from the computer.

With the jumpers in the USB position (i.e. on the two pins nearest the edge of the board), the DOUT pin the Xbee module is connected to the RX pin of the FTDI chip, and DIN on the Xbee module is connected to the TX pin of the FTDI chip. This means that the Xbee module can communicate directly with the computer - however, this only works if the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk to the Xbee module."

That means I will not be able to build what I want with this configuration?
I already tried, but didn't work.


texts: Leonardo Serial1 enable internal pull-up for removable Bluetooth module

texts:
I would like to have a serial Bluetooth module thats completely removable, leaving nothing connected to the arduino.

My code would freeze up whenever the Bluetooth module was removed. I eventually tracked down the issue to an overwhelming amount of garbage being received from the disconnected serial pins.

I enabled the internal pull-up resistor on pin 0 (serial rx) in the setup() function which appears to have solved all my problems but is that correct? I found barely any information on removable serial devices, floating serial connections and pull-up resistors.

I suppose it's important to enable the pull up before calling serial1.begin() or maybe flushing the serial buffer once before reading any input to ensure there's no garbage?


texts: is there any way I can run an MG2639 GPS Cellular Shield (the one SparkFun makes) on an Arduino Uno for GPS tracking purposes? It seems whether I use New or AltSoftSerial, the unit just can’t read what’s streaming in through from the GPS on the 115200 baud rate, which the shield is hard-wired to.


texts: Programming an Arduino BT-V06 using an UNO using ICSP

texts:
I have an Arduino BT-V06 laying around which I can't program over bluetooth for some reason. To be honest I don't understand the exact problem, but the problem is described in the question https://electronics.stackexchange.com/questions/7843/arduino-bt-upload-problem.

To solve the problem of programming the board I'm trying to program the BT-V06 using an Arduino Uno. I wired it all up using the description at https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader. The UNO seems fine, but the BT-V06 has the BATT-LOW led burning.

I've programmed the Arduino UNO using the Arduino ISP sketch. I've set the Arduino IDE to the COM port of the UNO, the target board to Arduino BT and the programmer to "Arduino as ISP". When trying to program the blink sketch I get the following error:

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 28,672 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: verification error, first mismatch at byte 0x0002
         0x40 != 0x5c
avrdude: verification error; content mismatch

Could it be that the power requirements are too high to be powered through the UNO?


texts: Extract binary numbers from infrared sensor that uses I2C bus

texts:
I have an infrared sensor(OTI 301) which in order to display the desired temperature I need to apply a formula that depends on 3 binary numbers extracted from the sensor itself. I have tried different approaches but no success yet to extract these binary numbers. Please see link for the data sheet of the sensor where you can see useful information regarding the formula and the binary numbers. https://drive.google.com/file/d/1XMRDCNzY3fn0q6lkGejs5D-pqksfRuZ8/view also here is the code I have tried in the Arduino IDE. Also, attached picture are the needed commands to extract the data from the second data sheet, https://drive.google.com/file/d/1mmdkHkNbwC5VgQxGMrq07XolajNvgBkN/view.

#include <Wire.h>
byte val[2] = {0x20,0x80};
void setup() {
Wire.begin(0x20);        // join i2c bus (address optional for master)
Serial.begin(9600);  // start serial for output
}

void loop() {

  //master writter
  Wire.beginTransmission(0x20); // transmit to device
  Wire.write(val,2);
  //Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  //master reader
  Wire.requestFrom(0x20, 6);    // request 6 bytes from slave device

  while (Wire.available()) { // slave may send less than requested
  Serial.println("H");
  char c = Wire.read(); // receive a byte as character
}

delay(500);
}


texts: Specific ports on Teensy 3.6 not reading correct bit resolution using ADC library?

texts:
I have a basic circuit, where I'm reading analog values from 14 infrared receivers.

I set the bit resolution to 16 but specific ports are returning 10 bit values (from 0 - 1024) instead of 16 bit values (from 0 - 65536).

I can confirm this is not a problem with my circuitry because when I've tested reading each individual sensor with a port that "works" and the correct range is returned every time.

Here is my code:

#include <ADC.h>

ADC *adc = new ADC();
const int* RECIEVERS = (int[14])
{
    A15, A16, A17, A19, A20, A21, A22, A1, A2, A3, A6, A7, A8, A9
};

void setup() {
    Serial.begin(4608000);
    adc->setAveraging(16); // set number of averages
    adc->setResolution(16); // set bits of resolution
    adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS);
    adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED);
    for (int i = 0; i < 14; i++) pinMode(RECIEVERS[i], INPUT);
}

void loop() {
    for (int i = 0; i < 14; i++) {
        Serial.print(adc->analogRead(RECIEVERS[i]));
        Serial.print(" | ");
        delay(1);
    }
    Serial.println("");
}

Is there a problem with my code or is my Teensy damaged?


texts: No response in Serial Monitor from es8266 with Arduino nano

texts:
I have exactly this model of esp8266:

I removed Atmega328p IC from Arduino, and powered Arduino with USB cable. After all, I made this connection combinations:
1)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

2)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

3)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd

4)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd

I checked both 9600, and 115200 baud, but on any of them I did not get a reply to the AT command. Have I done something wrong? I get weird characters when disconnecting ESP's GND wire, so some communication exists.


texts:
I'm trying to get the potentiometer seen at the top left of the photo to work, essentially as a dimmer. I've managed to upload the Arduino sketch, but it isn't working. Any help would be greatly appreciated!
NB: I have little-to-no electronics experience so my understanding of jargon is limited.

Thanks!

/*
 SENSOR_LIGHTS: Potentiometer >> LED (Single Channel Script)

 This example dims light levels using an LED on pin 11
 and a potentiometer on A0.

 Created by Ryan Achten | SOMA | somavisions.com

 This example code is in the public domain.
 */

int potentLevel;
int ledLevel;

//*************************CHECK*****************************

int led = 11;           // the pin that the LED is attached to
int inputPin = A0;      // the pin that the potentiometer is attached to

//*************************CALIBRATE*************************

const int numReadings = 1;  //change this to alter the number of values to be averaged
int potentMin = 280;
int potentMax = 700;        //maximum output from potentiometer
int loopDelay = 100;       //delay time between loops. Too low may cause overclocking
//                            while too high may cause delayed sensor response

//***********************************************************

int potentAve = 0;
int readings[numReadings];
int index = 0;
int total = 0;

// the setup routine runs once when you press reset:
void setup()  {

  //*************************POTENT >> LED SETUP CODE*************************

  Serial.begin(9600);

  pinMode(led, OUTPUT);

  //***************************SMOOTH SETUP CODE*****************************
  // initialise all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++)
    readings[thisReading] = 0;

}

//****************************SMOOTH LOOP CODE****************************

void loop()  {

  total= total - readings[index];
  readings[index] = analogRead(inputPin);
  total= total + readings[index];
  index = index + 1;

  if (index >= numReadings)
    index = 0;

  potentAve = total / numReadings;
  Serial.print("Average Potentiometer Readings: ");
  Serial.println(potentAve);

  //*************************POTENT >> LED LOOP CODE*************************

  ledLevel = map(potentAve, potentMin, potentMax, 0, 255);
  Serial.print("LED Level: ");
  Serial.println(ledLevel, DEC);
  analogWrite(led, ledLevel);

  Serial.println();
  delay(loopDelay);

}


texts: What is the capability of AVRISP and USBASP on ATMega48, 328, 2560?

texts:
For use with ATMega 48 (old Arduino?), 328 (UNO, Pro Mini) and 2560 (Mega2560) chips, what is the capability for the AVRISP and USBASP programmers on:

Can it read, write fuse?
Can it read, write Program Flash?
Can it work 3.3 and 5 volts?
What workable clock frequency range on the MCU?
Can it be used under Arduino ISP to write to board so as to erase the bootloader and use the FULL flash space for big user program (eliminate boot loader saves 0.5 to 8KB space on above Arduino boards)?
Can it be used with ATMel factory software development tools (Atmel studio and associated tools) to use MCU on chip hardware based breakpoint (Debug wire, JTag, or other names, as on different MCU)?

Many thanks in advance


texts: How to control low power devices when implementing Low Power Mode strategy?

texts:
As part of implementing Low Power Mode, I wish to control power to attached devices, such as the HC12 transmitter/receiver.  I've read of the usage of MOSFETs to control motors and lighting systems, but don't understand the applicability of such implementations to control something like an HC12, which consumes approximately 200ma.
Should I be using MOSFET and, if so which one?  Else, what is a better solution?  The circuit I am now working on is essentially a PRO Micro, an HC12, and a small led, though I will later add a camera module, approx. 100ma.


texts: Interface Processing with Arduino to operate a servo by MouseX

texts:
I want to make a servo change its angle using my mouse. When I move mouse horizontally the servo should change its angle correspondingly.
This is the sketch I wrote, unfortunately the servo doesn't move one bit. HELP.

Processing Code:

import processing.serial.*;
Serial port;
void setup() {
  size(256, 150);
  println("Available serial ports:");
  // if using Processing 2.1 or later, use Serial.printArray()
  println(Serial.list());
  port = new Serial(this, Serial.list()[1], 9600);
}

void draw() {
  // draw a gradient from black to white
  for (int i = 0; i < 256; i++) {
    stroke(i);
    line(i, 0, i, height);
  }
  // write the current X-position of the mouse to the serial port as
  // a single byte
  port.write(mouseX);
  println(mouseX);
}

Arduino Code:

#include <Servo.h>
Servo myservo;
void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
  // initialize the servo:
  myservo.attach(10);
}
void loop() {
  byte pos;
  // check if data has been sent from the computer:
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    pos = Serial.read();
    // set the angle of the servo:
    myservo.write(map(pos, 0, 255, 0, 180));
  }
}


texts:
I found this post and I am having almost the exact same issue. Nick Gammon (the god of arduino) has an excellent answer but I can't for the life of me implement it myself. I am not an advanced user like the initial question asker.

So What I want to do is use 2 MCP23S17's (picture here).
I have been messing with one of them all week and have it reading like a charm. I am using the githib library by n0mjs710 to do this. But writing to one will not work.

Along with the zipped library is a few examples. I am trying to read some BCD switches off of one "input MCP" and then display the digits on the "output MCP"

I have used external pullups so I did make one change to the code by commenting out the call for pullups. Here is what Doesn't work:

#include <SPI.h>              // We use this library, so it must be called here.
#include <MCP23S17.h>         // Here is the new class to make using the MCP23S17 easy.

MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                                  // and slave-select on Arduino pin 10
MCP outputchip(2, 10);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                                  // and slave-select on Arduino pin 10

void setup() {
  inputchip.begin();
  outputchip.begin();
  inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
  //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
  inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
  outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
}

void loop() {
  int value;                        // declare an integer to hold the value temporarily.
  value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
  outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
  // outputchip.digitalWrite(inputchip.digitalRead()); // this one line replaces the three above, and is more efficient
}

I have tried:

slowing the SPI bus by changing the library to SPI_Divide the clock by 2
changing the ss line and even splitting the lines so one chip uses pin 10 and the other uses pin 9

So after reading Mr. Gammon's post I have made some changes to the code attempting to rid myself of the old slave select pin low trick he mentioned. Here is my attempt:

MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                                  // and slave-select on Arduino pin 10
MCP outputchip(2, 9);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                                  // and slave-select on Arduino pin 10
int ssPin = 9;

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

  inputchip.begin();
  digitalWrite(ssPin, HIGH);
  digitalWrite(ssPin, LOW);
  outputchip.begin();
  inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
  //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
  inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
  digitalWrite(ssPin, HIGH);
  digitalWrite(ssPin, LOW);
  outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
}

void loop() {
  int value;
  // declare an integer to hold the value temporarily.
  value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
  digitalWrite(ssPin, HIGH);
  digitalWrite(ssPin, LOW);
  outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
}

So any advice would be great to get this working. Help me Obi wan Gammon your me only hope.


texts: How do I add dimming control to my following LED toggling program on Arduino? Also how do I improve my existing code?

texts:
I am attaching my code below :

int cwled=9;
int wwled=10;
int button=8;
int buttonpress;
long startTime=0;
long endTime;
long holdTime;
boolean previous = LOW;
boolean current;
int state=0;
int pot = A0;
boolean cwState = HIGH;
boolean wwState = LOW;
int brightness;
int counter = 1;
boolean pressB;

void setup(){
  pinMode(cwled,OUTPUT);
  pinMode(wwled,OUTPUT);
  pinMode(button,INPUT);
  Serial.begin(9600);

}

void loop() {
  if(state == 0){
    brightness= map(analogRead(pot),0,1023, 0, 255);
        analogWrite(cwled,brightness);
       // analogWrite(wwled,0);
        Serial.println("Initialized");
  }
  current= digitalRead(button);
  if(current == HIGH){
  pressDetection();
  state =1;
  }
}

void pressDetection(){
  pressB=digitalRead(button);
  if(pressB==HIGH && previous == LOW)
  {
    state =1;
    startTime = millis();
  }
  while(digitalRead(button) == HIGH){
    endTime = millis();
    Serial.println("Inside loop");
  }
  previous = LOW;
  holdTime = endTime - startTime;
  if(holdTime> 500){
    longPress();
  }
  else{
    shortPress();
  }

  }

void shortPress(){
  cwState = !cwState;
  wwState = !wwState;
  //brightness= map(analogRead(pot),0,1023, 0, 255);
  if(cwState == HIGH && wwState == LOW){
   brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(cwled,HIGH);
   digitalWrite(wwled,LOW);
   Serial.println("cwState");
   return;
  }
  if(cwState == LOW && wwState == HIGH){
  // brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(wwled,HIGH);
   digitalWrite(cwled,LOW);
   Serial.println("wwState");
   return;
  }
 /*else if(cwState == HIGH && wwState == HIGH){
   //brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(cwled,HIGH);
   digitalWrite(wwled,LOW);
  }*/
}

void longPress(){

   cwState =wwState = HIGH;

   //if(cwState == HIGH && wwState == HIGH){
 //  brightness= map(analogRead(pot),0,1023, 0, 255);
   digitalWrite(wwled,HIGH);
   digitalWrite(cwled,HIGH);
  cwState = !cwState;

 //}

}

I understand there are so many variables unused, this program needs a lot of improvising.
My question is:

How do I improve this code?
How do I add dimming via pwm in this code?
And if I have to add one more type of LED or say n number of LEDs and want to toggle between them what should be the algorithm.

My aim is to use a push button to switch between different types of LEDs (in my case between warmwhite LED and coldwhite LED, if Arduino registers long press off the push button all the LEDs light up, in my case both warmwhite and coldwhite LEDs turn on, and short press of push button toggles between warmwhite and coldwhite LED. The program by default switches on coldwhite LED first and after a long press, shortpress sets default LED to high which is coldwhite.

I am not a hardcore programmer but I have more than basic knowledge of OOPS programming. I am an ECE Engineer and I believe I have slightly more than basic understanding of OOPS and procedural programming. I am aware of C++, C and JAVA only. Any advice or help would be highly appreciated.


texts: Dynamically modifying the call stack using pointers

texts:
In a C++ Arduino library, can we modify the call stack from inside a function by intentionally decrementing a pointer to a stack variable so that it's out of range? Like this:

void FooBar()
{
  char a;
  char *ptr = &a;
  ptr -= 4;
  // Can we edit the call stack with ptr now?
}

Can we use this to, for example, change what function is "calling" FooBar() by replacing the function pointer of the calling function on the call stack to another function? Or can we change the values of function variables in the calling function in mischievous fashion?


texts: Odd RGB matrix behavior while using shift registers

texts:
so I'm playing around with an 8x8 RGB matrix using a 74HC595 shift register for each of the colors. I've done this before with single color matrices and everything worked fine, but here I'm getting some weir behavior that I can't really understand.

All 3 74HC595's are wired identically:
MR - 5v,
OE - Ground,
VCC - 5v,
GND - Ground

Latch and clock are shared between the registers.

The result:

This is not how it should look, do I have a timing issue somewhere? Thanks in advance!

The code:

int clock_pin = 3; // SH_CP
int latch_pin = 4; // ST_CP

int r_data_pin = 2;  // DS
int g_data_pin = A0;
int b_data_pin = A1;

int row1 = 5;
int row2 = 6;
int row3 = 7;
int row4 = 8;
int row5 = 9;
int row6 = 10;
int row7 = 11;
int row8 = 12;

const int row_count = 8;
const int col_count = 8;

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

  pinMode(row1, OUTPUT);
  pinMode(row2, OUTPUT);
  pinMode(row3, OUTPUT);
  pinMode(row4, OUTPUT);
  pinMode(row5, OUTPUT);
  pinMode(row6, OUTPUT);
  pinMode(row7, OUTPUT);
  pinMode(row8, OUTPUT);

  pinMode(clock_pin, OUTPUT);
  pinMode(latch_pin, OUTPUT);

  pinMode(r_data_pin, OUTPUT);
  pinMode(g_data_pin, OUTPUT);
  pinMode(b_data_pin, OUTPUT);

  digitalWrite(latch_pin, HIGH);
  digitalWrite(clock_pin, HIGH);

  digitalWrite(r_data_pin, HIGH);
  digitalWrite(g_data_pin, HIGH);
  digitalWrite(b_data_pin, HIGH);
}

namespace RGB {

typedef struct pixel {
  byte r;
  byte g;
  byte b;
};

}

int r_data[8][8] = {
  {0, 1, 1, 0, 0, 1, 1, 0},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {0, 1, 1, 0, 0, 1, 1, 0},
  {0, 1, 1, 0, 0, 1, 1, 0},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {0, 1, 1, 0, 0, 1, 1, 0}
};

int g_data[8][8] = {
  {0, 1, 1, 0, 0, 1, 1, 0},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {0, 1, 1, 0, 0, 1, 1, 0},
  {0, 1, 1, 0, 0, 1, 1, 0},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {0, 1, 1, 0, 0, 1, 1, 0}
};

int b_data[8][8] = {
  {0, 1, 1, 0, 0, 1, 1, 0},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {0, 1, 1, 0, 0, 1, 1, 0},
  {0, 1, 1, 0, 0, 1, 1, 0},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {1, 1, 1, 1, 1, 1, 1, 1},
  {0, 1, 1, 0, 0, 1, 1, 0}
};

void loop() {
  for (int row = 0; row < 8; row++) {
    digitalWrite(latch_pin, LOW);

    if (row == 0) digitalWrite(row1, HIGH);
    if (row == 1) digitalWrite(row2, HIGH);
    if (row == 2) digitalWrite(row3, HIGH);
    if (row == 3) digitalWrite(row4, HIGH);
    if (row == 4) digitalWrite(row5, HIGH);
    if (row == 5) digitalWrite(row6, HIGH);
    if (row == 6) digitalWrite(row7, HIGH);
    if (row == 7) digitalWrite(row8, HIGH);

    for (int i = 0; i < 8; i++) {
      digitalWrite(clock_pin, LOW);

      digitalWrite(r_data_pin, r_data[row][i]);
      digitalWrite(g_data_pin, g_data[row][i]);
      digitalWrite(b_data_pin, b_data[row][i]);

      digitalWrite(clock_pin, HIGH);
    }
    delay(1);
    if (row == 0) digitalWrite(row1, LOW);
    if (row == 1) digitalWrite(row2, LOW);
    if (row == 2) digitalWrite(row3, LOW);
    if (row == 3) digitalWrite(row4, LOW);
    if (row == 4) digitalWrite(row5, LOW);
    if (row == 5) digitalWrite(row6, LOW);
    if (row == 6) digitalWrite(row7, LOW);
    if (row == 7) digitalWrite(row8, LOW);
    digitalWrite(latch_pin, HIGH);
  }
}


texts: I am new to electronics and learning how to play around with arduino. I recently purchased the Arduino ultimate GPS Logger, and despite also buying an external anntenae the GPS data shows that it does not fix at all. Despite leaving the unit powered for more than 5 minutes. Please advise on what could be wrong. Is it normal to take so long to get a GPS fix? This is the Arduino in question. https://learn.adafruit.com/adafruit-ultimate-gps-logger-shield/overview


texts: Passing user defined callback functions to a library method

texts:
I developed an Arduino library that have a method called "process". This method is a Void function and must be called inside the loop and most of the time the library handles everything by it self:

#include <HookNinja.h>

HookNinja hookninja;

void setup()
{}

void loop()
{
  hookninja.process();
}

The idea is to keep the user program a simple as possible. Sometimes "process" have some data to give back to the user so he can use it as he likes. A simple approach is not to make process void and make the user check for the return value of process:

void loop()
{
  someVariableType foo;
  foo = hookninja.process();
  if(foo) {
    //user defined things
  }
}

But the data returned by process could be anything, from an int to an array of Strings, only the user knows the return type, also this method seems not very elegant. Im not an expert of C++, for me the ideal solution will be an object oriented approach were the user pass a function to process that can be called from the library, but I have no idea how to do this in C++, something like:

void userFunction(type param) {
  //do something with param
}

void loop() {
  hookNinja.process(some how pass userFunction here)
}


texts:
I am working on an Project in which i have to upload hex file from java to arduino uno i wrote the code in java its working but only when i call it in main method. But when i call it when button is pressed it doesn't upload the hex.

public class Main extends Application {
@Override
public void start(Stage primaryStage) throws IOException {

    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
    Parent root = loader.load();
    MainController controller = (MainController) loader.getController();
    Scene scene = new Scene(root,485,355);
    primaryStage.setScene(scene);
    primaryStage.setTitle("Hello World!");
    primaryStage.show();

    controller.Init(primaryStage);
    controller.searchForPorts();
    controller.disableControls();
}

public static void main(String[] args) {
     Avr avr = new Avr();
    avr.start();
    launch(args);
}

}

Working fine like this but when called on button pressed event doesn't work.

public class Avr extends Thread {
String avrdude;
String avrconf;
String hex ;

MainController main;
void setup() throws IOException{
    Path avrpath = Paths.get("avrdude.exe");
    Path hexpath = Paths.get("sketch_may13b.ino.hex");
    Path avrconfpath = Paths.get("avrdude.conf");
    Path realavrpath = avrpath.toRealPath(LinkOption.NOFOLLOW_LINKS);
    Path realhexpath = hexpath.toAbsolutePath();
    Path realavrconfpath = avrconfpath.toAbsolutePath();

    avrdude = realavrpath.toString();
    avrconf = realavrconfpath.toString();
    hex  = realhexpath.toString();

    avrdude = avrdude.replace("\\","\\\\");
    avrconf = avrconf.replace("\\","\\\\");
    hex = hex.replace("\\","\\\\");
    main = new MainController();

    String port ="COM3";
        runCommand(new String[]{avrdude, "-C"+avrconf,"-v","-v","-v","-v","-patmega328p","-carduino","-P"+port,"-b115200","-D","-Uflash:w:"+hex+":i"});

  }
  void runCommand(String[] cmd){

try {

Runtime.getRuntime().exec(cmd);

}
        catch (IOException e) {

      System.out.println("something went wrong: \n");
      e.printStackTrace();
  }

  }

@Override
public void run() {
    // TODO Auto-generated method stub
    try {
        setup();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}


texts:
int lightPin = 13;
int buttonPin = 2

void setup() {
  pinMode(lightPin, OUTPUT); //red
  pinMode(buttonPin, INPUT);
}

void loop() {
  int buttonValue = digitalRead(buttonPin);

  if (buttonValue == HIGH) {
    digitalWrite(13, HIGH);
  }  //red

  digitalWrite(13, LOW);//red
}  //red


texts:
I am trying to time how long button is held for. The code seems to work but with two problems:

the millis values are being read wrongly. If you hold the button for 1 second, it returns holdTime of about 3000 ms. A quick click returns holdTime of about 1000 ms.

Each successive button press adds to the previous millis value so holdTime just gets higher and higher and doesn't measure how long the button has just been pressed for

Any ideas or advice for newbie welcome!
#include <LiquidCrystal.h>

const int button1Pin = 1;  // pushbutton 1 pin
const int ledPin = 13;     // LED pin

int button1State, button2State;  // variables to hold the pushbutton states
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int startPressed = 0;
int endPressed = 0;
int holdTime = 0;

void setup() {
  // Set up the pushbutton pins to be an input:
  pinMode(button1Pin, INPUT);

  // Set up the LED pin to be an output:
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
\
}

void loop() {

  while (digitalRead(button1Pin) == LOW) {}

  button1State = digitalRead(button1Pin);
  startPressed = 0;
  endPressed =0;
  holdTime = 0;

  // if button1 or button 2 are pressed (but not both)
  if (button1State == LOW) {
    digitalWrite(ledPin, LOW);   // turn the LED on
    startPressed = millis();
  } else {
    digitalWrite(ledPin, HIGH);  // turn the LED off
    endPressed = millis();
    holdTime = endPressed - startPressed;
  }
  lcd.print("You pressed for");
  lcd.setCursor(0, 1);
  lcd.print(holdTime);
  lcd.print("ms");
  while (digitalRead(button1Pin) == LOW) {}
  lcd.clear();
  startPressed =0;
  endPressed =0;
  holdTime = 0;
}


texts: Weird sketch size/memory/compiler (?) related issue (hanging, RX led on)

texts:
Also posted at: https://forum.arduino.cc/index.php?topic=549672.0

is there anyone who experienced similar problem or knows a solution to it?

The problem is that after uploading the code Arduino Pro Micro hangs (and RX led is constantly on).

The problem occurs instantly after turning on the microcontroller even if I put "delay(10000);" at the begining of the code trying to see at which point the error occurs.

The problem can be "fixed" by adding 'Serial.print("aa");' at random place within the code...
Which results in the following output during upload:

Sketch uses 18318 bytes (63%) of program storage space. Maximum is 28672 bytes.
Global variables use 1814 bytes (70%) of dynamic memory, leaving 746 bytes for local variables. Maximum is 2560 bytes.

Suprisingly, using 'Serial.print("a");" instead does not fix the problem. It results in the following output during upload:

Sketch uses 18314 bytes (63%) of program storage space. Maximum is 28672 bytes.
Global variables use 1810 bytes (70%) of dynamic memory, leaving 750 bytes for local variables. Maximum is 2560 bytes.

It seems very weird to me that adding serial print instruction with certain length (at seemingly random place) can solve such problem...

Another circumstance which seems to be solving the problem is commenting out one of the 2 lines (does not matter which):

sprintf(at_cmd, "AT+NAME%s\0", bluetoothName);
sprintf(at_pin_cmd, "AT+PIN%s\0", pin);

It's a spaghetti code so I doubt anyone will analyse it but just in case if anyone wanted to check it for some more or less obvious characteristic (e.g. F()/eeprom/memory extensive use or something...) then here it is: Hastebin - link

I'm using "Arduino Pro Micro 5V" and Arduino IDE 1.8.5 with "Arduino Leonardo" board setting


texts:
I am trying to get my Arduino to send data to my computer using Node.js Serial port. Everything compiles, my Arduino is working well and sending data in the serial monitor, but the program always goes into myPort.on('close'), and I can't figure out why.

//import serial port js package
const SerialPort = require('serialport');

//opening a port
var myPort = new SerialPort("/dev/ttyS2", {
  baudRate: 9600,
  //parser: SerialPort.parsers.raw
});

//how to pass the readline
const Readline = SerialPort.parsers.Readline;
const parser = new Readline();
myPort.pipe(parser);

myPort.on("open", onPortOpen);
myPort.on("data" , onData);
myPort.on("close" , onClose);
myPort.on("error" , onError);

function onPortOpen(){
    console.log("Port open");
}

function onData(data){
    console.log("data transfer completed..");
    console.log(data);
}
function onError(){
    console.log("Error. something went wrong..")
}
function onClose(){
    console.log("Port is closed. Communication terminated");
}

Would anyone know what are the potential reasons? I double checked my port and it really is COM3, therefore, /dev/ttyS2 for Windows 10.


texts: Arduino Fried? Power is being delivered to Arduino but COM not found

texts:
When i connect my arduino nano to windows 10; the arduino nano is powered on (the "POW" led is on and not blinking; none of the others are on) but it doesn't show up on my computer. It used to but I think I may have shorted it.

Oddly, I get a measurement of 5V coming from digital pins 2,3,4 if connected through USB or 12V if I connect external power source to V_in. These are the pins that were on before what I believe was a short. Can someone tell me what is the component that is damage and whether it is possible to fix. Thanks!


texts: Ethernet.h Ethernet.Begin(mac) only connects if i have a LiquidCrystal object from LiquidCrystal.H

texts:
I have the following code;

#include <Ethernet.h>
#include <SPI.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(31, 30, 29, 28, 27, 26, 25, 24, 23, 22);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetClient client;

void setup()
{
  Serial.begin(9600);
  //client.begin(mac);
  //Init Ethernet Comms
  Serial.println(F("Start."));
  while (!Ethernet.begin(mac) == 0) {
    Serial.println(F("Network Error"));
    delay(200);
  };
  Serial.println(F("Connected"));

}

void loop() {}

As it is above it gets out of the while loop. However, if i remove the line LiquidCrystal lcd(31, 30, 29, 28, 27, 26, 25, 24, 23, 22);It will then fail to connect, and stay in the loop. Im at a complete loss here as the Ethernet shield and 2x16 LCD are unrelated devices, and if anything id expect the addition of used pins to cause issue, not the removal.

Edit: I should note this is occurring on two devices, one Mega one Uno.

2nd Edit: As pointed out by Juraj in the comments, this can be resolved using Ethernet.Init(CS_Pin) where CS_Pin is an unused pin, in my case D9.


texts: analogWrite never outputs a non-zero voltage

texts:
With a very simple connection of an LED (which can withstand 5V) to ground and to a pin on my Galileo gen2, I can never output a non-zero voltage from the pin via analogWrite, regardless of whether the pin is digital or analog (although PWM digital works)

The LED is in the correct bias and I'm calling pinMode(pin, OUTPUT) before attempting to call analogWrite(pin, 255) (or any 2nd parameter in-between), even though it's not even necessary.
The LED glows if I call digitalWrite(pin, HIGH) on both analog and digital pins, but does not glow at all for analogWrite(pin, 255) with the same configuration and pins, nor does it for any 2nd param in [0, 255]. This holds for whether the call is attempted in loop() or setup().

The only possible way I can get the LED to receive any power from analogWrite is through a digital PWM pin, but I know the other digital pins can still produce square-waves with timers and the analog pins should certainly be able to use PWM.

(So far, I've been to scared of short-circuits to connect the analogWrite output straight into an analog input to read the voltage)

Is there something I don't understand about the underlying board, or am I experiencing some strange malfunction?

Thanks,
Tyson


texts:
I need to use a servo library in my class.
I read this question - Use object of other class within class and it works fine for my LCD application, but now I need to use a 2D servo array in my class. I made one approach, it worked, but I think it is bad programming approach, what is right way to solve my problem?

My main file

#include <SoftwareServo.h>
SoftwareServo servo[5][5];
Servolib Servoarray;

void setup(){
  blah blah blah

My cpp file

#include "Vending.h"
#include "Arduino.h"
#include <SoftwareServo.h>

Servolib::TurnSevo(){
  for(int row=0;row<5;row++){
    for(int collum=0;collum<5;collum++){
      servo[row][collum].attach(Object[row][collum]);
      servo[row][collum].write(0);
    }
  }
}

my .h file

#ifndef Vending_h
#define Vending_h
#include "Arduino.h"
#include <SoftwareServo.h>

class Servolib:SoftwareServo{
public:
  void TurnServo();

private:
  SoftwareServo servo[5][5];
  int Object[5][5]={
    {42,21,20,19,18},
    {37,41,36,38,35},
    {31,33,30,34,39},
    {67,28,66,29,65},
    {56,63,55,64,54}
  };
};
#endif

So this code worked, but please give me better solution.


texts:
I bought a ethernet shield for my Arduino Uno. I plug it my Arduino and PC with ethernet cable. There is all led is working on ethernet shield. But when i try to examples about ethernet which is in Arduino IDE as "DHCPChatServer" example.

I hope to see;
"Trying to get an IP address using DHCP"
"My IP address: 192.168.1.177"

But I just see "Trying to get an IP address using DHCP"

Any problem with my ethernet shield?


texts: arduino due: how to read more than one byte at a time in serial uart with tfmini liar sensor

texts: I'm trying read tfmini lidar sensor from arduino due board with uart. Here i can read only one byte at a time using serail.read() method but i need to read 9 byte at a time and store it in array. Means i don't want to repeat loop again and again to store byte by byte.


texts: How to boil down analog input to just three cases?

texts:
I am investigating the use of a 3-position-switch for one of my projects to switch between different settings using just one analog input pin. For the three positions I am using ground/0V, ~2.5V (via 2x10k voltage divider) and full 5V. I am doing this also because I am planning to use a 5-position rotary switch in a similar way in the future.

Due to tolerances and noise, the readings on the analog pin are not precisely 0, 511, 1023, but rather 0-1, 509-512 and 1021-1023. To take this into account, I am using the map function like this:

const byte alarmSwitchPin = A0;
int alrmSwState;
byte alrmSet;
byte alrmPrevSet;

void setup() {
  Serial.begin(9600);
  pinMode(alarmSwitchPin, INPUT);

}

void loop() {

  alrmSwState = analogRead(alarmSwitchPin);       // Read input

  byte alrmSet = map(alrmSwState, 0, 1023, 0, 2); // Boil input down to three cases

  if (alrmSet != alrmPrevSet) {                   // Only if state of switch has changed
    switch (alrmSet) {
      case 0:
        Serial.println("Low");
        break;
      case 1:
        Serial.println("Medium");
        break;
      case 2:
        Serial.println("High");
        break;
    }
    alrmPrevSet = alrmSet;
    delay(200);                                   // For testing purposes
  }
}

I only want the setting to change (or, in this case, the console to print) when the state has actually changed. This does not work, though, because the map function is doing its math in integer, which fails in mapping the High position (in this case).

What are my options if I want to stick with the switch method? I am curious if it is possible to get this done without if statements and conditions or, as a more general question, what the best option is to properly map the 10 bit analog input to just 3 cases/numbers.

PS: I thought analogReadResolution() might be an option but I am working with Arduino UNO where this is unavailable.


texts: How are the different sleep modes used for esp8266?

texts:
I am currently trying to power my esp8266 with a battery, but I want to decrease the power consumption (current mostly). I understand there are different sleep modes, but I do not understand what can I use for each sleep mode. I want to know what functions are still enabled during each sleep mode.
Example: Can I use ADC pins in modem sleep?
My biggest question:
I am sending beacon frames to my phone, I want to know if I can use one of these sleep modes while sending my beacons at the same time? Do I need my CPU or do I need my Clock to send frames?


texts: How to name the temperature sensors instead of printing address using ds2482-100 and ds18b20 sensor- Help

texts:
I am using 10 ds18b20 Temperature sensors using with "DS2482-100" I2C board and Arduino
so when I am getting the output like this:- "ROM = 28 46 04 1F 0D 00 00 74 96014B467FFF0A100A 25.3 2699 Dc", so Instead of address I want to name it "Sensor-1", "Sensor-2"  like that any tutorial or help would be appreciated.

`*
Arduino library for controlling DS2482-100 and DS2482-800 1-wire masters.
Uses Wire library to communicate with DS2482 so be sure to call Wire.begin() before using the library.
Quick example modeled after Onewire example:
*/
 #include <OneWire.h>
 #include <Wire.h>
 #include <DS2482.h>
 #include <DallasTemperature.h>

 DS2482 ds(0);  //channels ds2482-800 is 0 to 7, DS2482-100 is just set 0

 byte data[12]; //holding for onewire capture
 byte addr[8]; //1wire wire address and CRC
 long time_temp;

 uint8_t sensor1[8] = { 0x28, 0x00, 0xF9, 0x1E, 0x0D, 0x00, 0x00, 0x76 };
 uint8_t sensor3[8] = { 0x28, 0x61, 0x64, 0x12, 0x3F, 0xFD, 0x80, 0xC6 };

 void setup()
 {
    Wire.begin();
    ds.reset();
    pinMode(13, OUTPUT);

    // start serial port
     Serial.begin(57600);
     time_temp = millis();
 }

 void loop()
{

   //do search

  if ( !ds.wireSearch(addr))
  {
    if(addr == sensor1)
    {
    Serial.print("sensor1");
    };
 Serial.print("No more addresses.\n");
 ds.wireResetSearch();

return;
}

Serial.print("ROM =");
for ( int i = 0; i < 8; i++) {
Serial.write(' ');
if (addr[i] < 16) Serial.print("0");
Serial.print(addr[i], HEX);
}

if (ds.crc8(addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return;
}

//test if device code DS18b20
 if (addr[0] == 0x28) {

 //read temperature data.
  ds.wireReset();
  ds.selectChannel(0);
  ds.wireSelect(addr);
  ds.configure(0x05); //set bus on strong pull-up after next write until next command
  ds.wireWriteByte(0x44); //convert temperature on this device
  delay(770); //wait for conversion 750ms Plus margin
  ds.wireReset();
  ds.selectChannel(0);
  ds.wireSelect(addr);
  ds.wireWriteByte(0xbe);         // Read Scratchpad command

  //display hex values of scratchpad
  Serial.print(" ");
  for ( int i = 0; i < 9; i++)
  {

   data[i] = ds.wireReadByte();

  if (data[i] < 16)Serial.print("0");
  Serial.print(data[i], HEX);

}
  Serial.print(" ");

  //convert to decimal temperature

    int LowByte = data[0];
    int HighByte = data[1];
    int TReading = (HighByte << 8) + LowByte;
    int SignBit = TReading & 0x8000;  // test most sig bit
    if (SignBit) // negative
{
    TReading = (TReading ^ 0xffff) + 1; // 2's comp
}

    int Tc_100 = (double)TReading * 0.0625 * 10;

    if (SignBit) // If its negative
{
    Tc_100 = 0 - Tc_100;
}

  //print temp for each device

   Serial.print(Tc_100 / 10);
   Serial.print(".");
   Serial.print(Tc_100 % 10);
   Serial.print(" ");
   Serial.print(millis() - time_temp);
   Serial.println(" Dc");
   }

   }