texts: Arduino One Wire Bus DS18B20 self developed driver missing bits or extraneous bits

texts:
I recently got to code my own driver for the One-Wire-Bus specifically with the ubiquitous DS18B20 temperature sensor in mind for an application.

I am running that code on an Arduino Mega 2560. Programming is done in Atmel Studio 7 and an AVR ISP mk2.

In the version as-of yesterday see here I get missing binary digits while trying to send the 0x55 One-Wire-Command (i.e. Match-Rom-Code).
It appears like it where the least significant two bits that are missing (Oscilloscope capture).

Today I tried to sort out that bug and "fixed" it by counting to 9 instead of 8 (even though I can't explain why this should work, it should rather break stuff [turns out it does]...) and subtracting 1 from my index variable. (See file "OneWire.c" line 83 and following for the old version).
Todays version is here (compare file "OneWire.c" line 81 and following).

In the new version (as-of today) I am able to get the 0x33 opcode (i.e. Send-Rom-Command) transmitted as wanted and get the ID of my specific sensor on the bus (atleast my oscilloscope shows the correct waveform). In the newer version I do the following chain of operations:

get the ID of the single sensor I have connected at the moment
send the Match-Rom-Command (just because that is something actually meaningful to do)
send the 64-Bit Rom-Code after that (or atleast what ever the statemachine of the getID function did end up writing in the output parameter)
send the 0x44 opcode (i.e. start temperature conversion)

This scenario yields me no correct Rom-code being sent on the bus, one byte more on the bus and another single bit too much on the bus for the temperature-conversion opcode. The Match Rom Code command does get transfered as supposed to and does not yield any extraneous or missing bits (no scope capture for that since that would not be possible to get into one shot that shows it all [at a workable scaling]...).

I would highly apprechiate anyone looking at my code and trying to figure out what is going wrong here since I am completely in the dark right now.

Before anybody asks:

I specifically did not want to use the readily available One-Wire-Libraries as they tend to be bloated and heavily rely on the delay function, which is fine if you are doing little else with your chip but not else. Since I have multiple sensors to read out (not yet but as soon as I got the drivers working) have to do some post processing on the raw data (i.e. put some sort of math to it) and transmit that data on a usually slow interface (I2C, Serial, you name it), which all takes time (and all that [periodically and as fast as possible of-course] on a poor 8-Bit Micro that runs at a underwhelming 16MHz...), I decided to keep polling and delay()-uses to a minimum and rather rely (heavily?) on a timer interrupt and a series of Statemachines...

It is not at  all obvious to me why the code does act in that way.


texts: How to use analogWrite() on multiple pins at the same time?

texts:
I would like to do,

analogWrite(100,3);
 analogWrite(200,6);

at the same time. But the problem is that only the led on pin 3 lights up. I want both to light up at the same time. I've heard about direct port manipulation, but I can only find an alternate for digitalWrite() but I couldn't find one for analogWrite(). Can someone please help me with just a simple example on just how to do the above operation?

I'm using arduino uno.


texts:
Also asked in forum.arduino.cc

bool receive_command(char answer[]);
void serial_flush(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  for(byte i=0;i<3;i++){
if(receive_command("OK")) Serial.println("OK found");
 serial_flush();
  }
}

void loop() {}

void serial_flush(void) {
  while (Serial.available()) Serial.read();
}

bool receive_command(char answer[]) {
 unsigned long _time = 0;
  const int max_time = 10000;
  bool flag = 0;

Serial.print("in Serial buffer=");
  Serial.println(Serial.available());
  if(Serial.available()){
  Serial.write(Serial.read());
  Serial.println(" left in serial buffer");}

  while (Serial.available() < 2) {
if ((millis() - _time) > max_time) {
      Serial.println("waited too long nothing received");
  return flag;
    }
    }
  do {
    if (Serial.findUntil(answer, '\n')) return flag = 1;
  } while (Serial.available());

return flag;

}

via serial monitor with CR+LF line ending I`m sending this string:
abcdefghijklmnopqrstuvwxyzOKabcdefghijklmnopqrstuvwxyz
26chars+OK+26chars+CR+LF=56 chars

Output:

in Serial buffer=0
OK found
in Serial buffer=1
b left in serial buffer
in Serial buffer=0
waited too long nothing received

after OK is found serial_flush() is executed but after second run there serial.available() shows there is something in serial buffer. right at that moment it was char 'b' but it also can show char 'd'  and 'c' depending how long it will run.

why serial_flush() is not clearing the buffer?

Thanks.


texts: How do powering arduino both barrel jack and lipo battery together?

texts:
I have arduino mega and Lipo batterry such this and Lipo battery charger 5V USB Boost. I am powering arduino normally from barrel Jack with an 9 Volt adaptor. But if there is power cut occur, I dont want to stop, I want powering arduino with Lipo battery. After power come back, arduino contunie to powering from barrel jack again at the same time battery start to charge. How can I succes this. Do you have any sample circuit?
After Majenko♦ comment, I've tried circuit but there is heating problem occur. More then 70 celsius. Is that normal?
Circuit

Termal Circuit


texts: Arduino SPI Communication with H3LIS100DL accelerometer

texts:
I'm having trouble getting information off the accelerometer I'm trying to use. What code should I use to read the X,Y, and Z axis?  I've read the data sheet but I don't have any experience with SPI communication.

Spec sheet


texts: Unusualy high fail rate with Adafruit Circuit playgrounds

texts:
I am on my 4th failed Adafruit Circuit playground, I can usualy program them a few times, like less than 10, then they become unresponsive. no amount of reseting, rebooting, bootloader re-installations, etc seem to help.
I am using Arduino 1.8.1, on a linux platform, running on a Lenovo T510.

I have numerous other MCUs that have never failed... Im just curious why there is such a high failure rate with the circuit playgrounds I am getting.


texts:
On an esp8266 I want to create a little webserver that shows me a dashboard with charts and stuff. For this I wanna include the echarts-library as it works offline. To access it the only way I can see this working is that I write `
const char libData[784674] PROGMEM = "the entire 700 KB library goes here";

And then deliver it on request with server.on('./echarts.min.js', handleLibRequest) or something like that.
Now my problem is that in this 700KB of text there are ' and " characters all scattered arround. The C++11 way of R("hard escapable '"'''" string") isn't working in my environment. How would one go about this to include this file in my code?
Is there mybe some way utilize the preprocessor for this? Or maybe an online tool that converts "str" to ['s','t','r']?


texts:
I'm trying to make a kernel for a macro-key maker, this is the starting page's code:

char m[] = "What do you want to do? Type the following commands in this "
      "terminal:\nnew  --> Creates a new Keybinding\ndelete  --> Deletes a "
      "previous Keybind\nlookup --> Find what is bound to a key\n\nTurn off the "
      "switch to go back to the normal mode.";
Serial.println(m);
Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

When I run it, the screen displays:

What do you want to do? Type the following commands in this terminal:
new  --> Creates a new Keybinding
delete  --> Deletes a previous Keybind
lookup --> Find what is bound to a key

Turn off the switch to go back to the normal mode.

The last line is missing.  Is this a problem with object casting? takenKeybind is an int.


texts: (very new to C) I'm trying to use irsend with what I think is char* but it won't take it. How can I convert it to what it needs?

texts:
I'm attempting to use a raspberry pi to send ir codes directly to my arduino to have as simple as a C program as possible. Here's my code I've been tinkering with that leads to errors or not working if I don't specifically hardcode the hex ir signal.
#include <IRremote.h>

char buf[80];

String code = "empty";

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0; // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

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

IRsend irsend;

void loop() {
  if (readline(Serial.read(), buf, 80) > 0) {
    Serial.print("You entered: >");
    //Serial.print(buf);
    //Serial.println("<");
    //irsend.sendNEC((uint32_t) buf, 32);
    String str(buf);
    //irsend.sendNEC((uint32_t) code, 32);
    //irsend.sendNEC(0x210704FB, 32);
    code = buf;
    delay(600);
    //Serial.print((uint32_t) buf, 32);
    Serial.print(code);
    irsend.sendNEC(buf, 32);

  }

I've left my mess on the bottom to illustrate how little I know and what I've tried. I've been trying to figure out what I'm sending it but it doesn't help that serial.print doesn't work like irsend. I'm intending to send hex codes directly and have the arduino blindly plug them into irsend.sendNEC(0x210704FB, 32); which works but when I try to put my own variable in it won't.
Very much appreciate any help! I know it'd be easy for anybody who knows a little C.
irsend.sendNEC(buf, 32); returns:
initializing argument 1 of 'void IRsend::sendNEC(uint32_t, uint8_t, bool)'
void sendNEC(uint32_t data, uint8_t nbits, bool repeat = false);
and irsend.sendNEC((uint32_t) buf, 32); doesn't throw any errors but also does not seem to do anything


texts: so i replaced the mainboard in (what was) an anet a8 3d printer with a proper RAMPS setup. there was nothing wrong with it, (or at least it wasnt damaged, there are a number of severe design flaws) so i thought it might be a good start point for a remote controlled crawler/bot thing. it already has four a4988 drivers on board, plus a few mosfets and other bits which will be great for accessories (planning headlights, horn, maybe light sensor). its built around the atmega1284p, which is something of an oddball inbetween the 328 on the uno and the 2560 on the mega, but is the same product line. ive already worked out the libraries/drivers for the ch340 or whatever it is that is needed to flash code to the board,it already has already been added to the arduino ide, i have successfully flashed sketches to it before, but not my own. what im wondering is how to declare pins when im writing my own code. the bottom right of this schematic lists connections to the main chip, is it reasonably safe to assume that the digital pin numbers listed there can be used like the normally labeled headers on a standard board? how exactly are those numbers determined?


texts:
I have a simple setup with arduino Nano as slave and a arduino Mega as master
Can anyone explain how the function 15
FORCE_MULTIPLE_COILS
Works
i have been running some test on this
and cant figure out how to use the
local_start_address
is this the data to read from
or
is it a pointer to another File
modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 1021);
dec 8 = (no_of_registers = packet->data)  // number of coils
so frame 6 = 1 (frame[6] = no_of_bytes;) // number of bytes more
dec 1021 = (packet->local_start_address)
the dec 1021 and 65565 seams to work ????
but makes no sense to me in binary format ?
Here is
part of CPP file:
enter code here

unsigned char construct_F15()
{
   // function 15 coil information is packed LSB first until the first 16 bits are completed
  // It is received the same way..
  unsigned char no_of_registers = packet->data / 16;
  unsigned char no_of_bytes = no_of_registers * 2;

  // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad
  if (packet->data % 16 > 0)
  {
    no_of_registers++;
    no_of_bytes++;
  }

  frame[6] = no_of_bytes;
  unsigned char bytes_processed = 0;
  unsigned char index = 7; // user data starts at index 7
   unsigned int temp;

  for (unsigned char i = 0; i < no_of_registers; i++)
  {
    temp = register_array[packet->local_start_address + i]; // get the data

frame[index] = temp & 0xFF;

    bytes_processed++;

    if (bytes_processed < no_of_bytes)
    {
      frame[index + 1] = temp >> 8;
      bytes_processed++;
      index += 2;
    }
  }
   unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes
   return frameSize;
}


texts: How to start particular event for particular time using millis()?

texts:
In my recent project, I want to run particular event for the particular time. For example, If I want to Turn ON my LED for 20 Second. And rest time LED must be off. I know using delay() it is possible but If we used delay() function then that time we can't do anything. So, I tried out millis() for that. I tried the basic code for this.

The code is below:

const int ledPin =  LED_BUILTIN;

int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 5000;

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

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;

    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    digitalWrite(ledPin, ledState);
  }
}

But the output of this is like LED ON for 5 Second and then LED OFF for 5 Second. And this thing happens continuously.But I don't want this. I just want to turn ON LED for 5 Second when I want and then LED off forever. And I tried out many logics for that somehow can't able to get this thing. Someone suggest me some idea about this.


texts: How to send data to PC/app from sensors connected to Arduino

texts: I want to send data in real-time from the sensors connected to my Arduino project to my PC or Android app. I would like see any real-time changes detected by the sensors as a graph on the PC or inside a smartphone app. How to achieve that? Are there any telemetry software already available or do i need to code my own from scratch?


texts: Picking the time a led on an arduino should turn on, via android

texts: I have created an app which is connencted to my arduino via bluetoth. The user of the app can turn on and off a led which is connented to the arduino. But I want to take it a step further... I want the user to be able to give the time and the date when the light should turn on and additionally the time that sould pass until the led turns off again. Is it significantly harder? I have thought of using an already existing alarm app but I am pretty stuck, so could anyone give me some suggestions?


texts:
So I have a stepper motor that's rated for 2.9V and 0.8A and I connected it to a L9110 Driver and I wanted to drive it with my arduino. But I don't know how to drive it safely without damaging the motor. I am using the stepper.h library and thought of connecting it to 3.3V pin on the Arduino but I am a bit concerned.. is it Ok to power it with 3.3V if no then What can I do?
Edit: the L9110 module I am using is a dual H Bridge.
Edit2: I was Indead Powering the Stepper and the Module directly from the arduino.. luckily the arduino survived.
Edit3: So I didn't have a 3V power supply so I used a Voltage Divider with a 9V battery and connected the L9110s module with the battery (after its voltage divided) and the module powers on.. but when the arduino starts driving the stepper the module's led starts Flickering instead of staying on and the stepper doesn't turn... I don't know what is the problem.


texts: Only return button state once in X amount of time?

texts:
I want to detect if a button has been pressed, but what I don't want is for it to keep returning the "pressed" state more than once within a second or two.

For example, with this code:

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW) {
    Serial.println("PASSED!");
  }
}

Would spit out something like this with a single quick press of the button:

PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!

But what I want is for a single button press to just return PASSED! once for that single button press.


texts:
The problem started when I tried to upload the Blink program to the module, it uploaded with no issues through Arduino but after that the blue LED didn't blink.

I searched a lot for it and found that the pin number may need to be changed.

So I uploaded this code

int LED0 = 0;
int LED1 = 1;
int LED2 = 2;

void setup() {
  pinMode(LED0, OUTPUT); // Initialize the LED_BUILTIN pin as an output
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  Serial.print("LED_BUILTIN = ");
  Serial.print(LED_BUILTIN, DEC);
}

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

to ensure the blinking but still nothing out.

After that I tried AT commands and no replies also.
After that I did some searches and found that it may need to update the flash program and that's what I did.
No sync occurs until I remove and connect the power to the module while the tool is trying to sync. Otherwise, it gives a fail.
By removing and connecting the power to the module I was able to upload that flash,
But I still have the same problem - no reply from the module to AT commands and the blink output is nothing.
Finally I directly connected the TX to the 3.3 V and the blue LED is on so I figured that the problem is in the replying from the module.

Any help would be appreciated.


texts: Does SMS format depend on the sender's mobile?

texts:
I want to read the SMS using Arduino and GSM module, I want to perform conditional programming based on the received SMS.

What I found really interesting is SMS format is different if I send message from different phones.

Output of my code is

Case 1:(From a smartphone)

Mobile Number is: +91954xxxxxxx
Message Text: 5+22" Hello Arduino

Case 2:(From a normal phone)

Mobile Number is: +91984yyyyyyy
Message Text: Hello Arduino

Does it really depend on the sender's mobile phone? If yes, how to move further to make my code independent on the sender mobile.

My code is

//===final code

char RcvdMsg[200] = "";
int RcvdCheck = 0;
int RcvdConf = 0;
int index = 0;
int RcvdEnd = 0;
char MsgMob[15];
char MsgTxt[50];
int MsgLength = 0;

void Config() // This function is configuring our SIM900 module i.e. sending the initial AT commands
{
   delay(1000);
   Serial.print("ATE0\r");
   Response();
   Serial.print("AT\r");
   Response();
   Serial.print("AT+CMGF=1\r");
   Response();
   Serial.print("AT+CNMI=1,2,0,0,0\r");
   Response();
}

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

void loop()
{
   RecSMS();
}

void Response() // Get the Response of each AT Command
{
   int count = 0;
   Serial.println();
   while(1)
   {
      if(Serial.available())
      {
         char data =Serial.read();
         if(data == 'K'){Serial.println("OK");break;}
         if(data == 'R'){Serial.println("GSM Not Working");break;}
      }
      count++;
      delay(10);
      if(count == 1000){Serial.println("GSM not Found");break;}

   }
}

void RecSMS() // Receiving the SMS and extracting the Sender Mobile number & Message Text
{
   if(Serial.available())
   {
      char data = Serial.read();
      if(data == '+'){RcvdCheck = 1;}
      if((data == 'C') && (RcvdCheck == 1)){RcvdCheck = 2;}
      if((data == 'M') && (RcvdCheck == 2)){RcvdCheck = 3;}
      if((data == 'T') && (RcvdCheck == 3)){RcvdCheck = 4;}
      if(RcvdCheck == 4){RcvdConf = 1; RcvdCheck = 0;}

      if(RcvdConf == 1)
      {
         if(data == '\n'){RcvdEnd++;}
         if(RcvdEnd == 3){RcvdEnd = 0;}
         RcvdMsg[index] = data;

         index++;
         if(RcvdEnd == 2){RcvdConf = 0;MsgLength = index-2;index = 0;}
         if(RcvdConf == 0)
         {
            Serial.print("Mobile Number is: ");
            for(int x = 4;x < 17;x++)
            {
               MsgMob[x-4] = RcvdMsg[x];
               Serial.print(MsgMob[x-4]);
            }
            Serial.println();
            Serial.print("Message Text: ");
            for(int x = 46; x < MsgLength; x++)
            {
               MsgTxt[x-46] = RcvdMsg[x];
               Serial.print(MsgTxt[x-46]);
            }

            Serial.println();

            //****Resetting all the variables*****//

            //RcvdMsg[200]={0};
            RcvdCheck = 0;
            RcvdConf = 0;
            index = 0;
            RcvdEnd = 0;
            MsgMob[15];
            MsgTxt[50];
            MsgLength = 0;

            Serial.flush();

         }
      }
   }
}


texts: using special symbols from the U8glib library

texts: I enter font symbols into the u8g.setFont() and I get a string of sympols. How do I grab just one of those symbols, for example an arrow?


texts:
What is the simplest way to get an alarm sound when a human raise hands up.
Assuming he is wearing a sensor or whatever as a watch or ring.


texts:
I am building an ESP8266 device that uses RFID but need to conserve battery power.

The ESP is a Wemos D1 Mini and the RFID module is a RC522 (still waiting for it to arrive), which needs 3.3 V. I'm powering the ESP with a battery shield and 3.3 V.

But I don't want to connect the RFID module directly to the battery shield because it will be sucking voltage constantly. Instead, I want to be able to control its power using the ESP.

So I thought the easiest would be simply to connect the RC522's 3v3 line to one of the ESP's available GPIO pins, set it to output, and when I need  RFID, set the GPIO pin high, to turn on the RFID module.

Is this an acceptable solution, or do I need to wire in a transistor and capacitor somewhere?


texts: How do I "conditionally" include libraries and declare global objects of them?

texts:
I'm trying to write a generic "Test Bench" type of sketch using booleans to indicate whether or not to include specific libraries.  After those are defined, I'm attempting to use preprocessor #if statements to determine if the libraries need to be included and create the objects if need be.

Example:

const bool useLCD = true;

...

#if (useLCD)
  #include "NHD_4x20.h"
  NHD_4x20 lcd(9);
#endif

These statements are before the setup() and loop() functions.  This in itself doesn't generate compiler errors, however I get "lcd has not been defined in this scope" when trying to use the object in the setup() and loop() functions.

Is there some simple trick to accomplish this that I'm overlooking here ?

Thanks in advance !


texts: Problems with Dallas temperature sensor code

texts:
I have connected up my temperature sensor and I am trying to run the one wire address finder to find the address of the sensor.

The problem is that when I run the code it gives me the error: 'OneWire' does not have a type.

I have imported by the temperature and the onewire libraries but it still does not work.

#include <OneWire.h>

OneWire ds(6);  // This is where the error is


texts: Master doesn't receive the correct values in a master/slave SPI link

texts:
I've been struggling for 3 weeks looking for a solution to my problem concerning SPI communication.

So, I need to establish a SPI communication between two Arduino devices: for instance, the master sends a letter 'a' to the slave; the slave receives it and does some processing. In my case, it should set one of his  8 pins to high then read all pins and send the report back to the master.

The part where the master sends 'a' and the slave processing it works fine but the master doesn't seem to receive the correct values. Instead it always receives 0.

Here's the code:

Slave:

#include <SPI.h>;

volatile byte command = 0;
byte ett =8; //nbr of test points
byte motif= 0b000000000 ; //intiatition of my varible which will contain my pin's states
byte end[8] = { 2,3,4,5,6,7,8,9}; //array containing the pins

void setup (void) {
  Serial.begin (9600);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  // turn on interrupts
  SPCR |= _BV(SPIE);
}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect) {
  byte c = SPDR;
  switch (command) {
    //////////////Slave traitement/////////////
    // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  case 'z': ////case 'z", set all pins to INPUT
    for (int i=0; i<8; i++){
      pinMode (end[i], INPUT);
    }
    break;

  case 'a': // //if 'a' : Set one pin to high then read all pin's satete to verify if there is any open circuit or short circuit
    for (int j = 0; j < ett; j++) {
      pinMode(end[j], INPUT);   // set all pins as INPUT
    }
    motif = 0;
    pinMode(end[0], OUTPUT);  // Set one pin as OUTPUT
    digitalWrite(end[0], HIGH); // Set the output pin to HIGH
    Serial.println();
    Serial.print(" ");
    for (int k = 0; k < ett ; k++) { // scan
      if (digitalRead(end[k]) == HIGH) {
        // if pin == HIGH add '1' to my vector
        Serial.print("| ");
        motif = motif + 1; // +1
      } else { // if pin == LOW
        Serial.print(". ");
      }
      motif = motif << 1; // shift left
    }
    Serial.print(" -MOTIF LU= ");
    Serial.print(motif, BIN);
    SPDR = byte (motif); //SPDR is the SPI Data Register: it contains the data that will be sent to the Master
    Serial.print(" ");
    break;
  }
}

void loop (void) {
  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
}

Master:

#include <SPI.h>

byte CS0=10;
byte CS1=9;

void setup (void) {
  Serial.begin (9600);
  Serial.println ();
  digitalWrite(SS, HIGH);  // ensure SS stays high for now
  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();
  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);
}  // end of setup

byte transferAndWait (const byte what) {
  byte a = SPI.transfer (what);
  delayMicroseconds (1000);
  return a;
} // end of transferAndWait
///traitement au niveau du maitre

void loop (void)  {
  byte esclave0_testpin0;
  /////////////Set the first slave's pin to High then read all pins
  digitalWrite (CS0,LOW); //activate the slave
  transferAndWait ('a'); // set first slave's pin to high
  esclave0_testpin0 = transferAndWait ('z'); //read all slave's pins and report it in the variable esclave0_testpin0
  digitalWrite (CS0,HIGH); //disactivate the slave
  Serial.println ("test_0");
  Serial.println (esclave0_testpin0, BIN);
  delay (1000);  // 1 second delay
}  // end of loop


texts:
I just make a simple circuit with uno and breadboard ,that connected 4 LED and 4 IR sensor. The arduino program is simple that makes the light on or off with the determination of IR sensors .
However my computer cannot find the USB COM when it connects the 5v and GND.
Hence, I plug out the 5v and GND that connect to the breadboard .The computer can recognize COM 4 then . I successfully upload the program after this .
Now , when I connect the computer and UNO to give battery to UNO , no battery passed (because the computer cannot detect the USB COM) .The lights of IR sensor aren't on .How to tackle the problem?
It failed to  give battery with external battery too unless I plug out the 5v and GND
This is my simple program:
int irPin1 = 2;
int ledPin1 = 13;
int irPin2 = 3;
int ledPin2 = 11;
int irPin3 = 4;
int ledPin3 = 9;
int irPin4 = 5;
int ledPin4 = 7;
int serialSpeed = 9600;

void setup() {
  // put your setup code here, to run once:
  pinMode(irPin1,INPUT);
  pinMode(irPin2,INPUT);
  pinMode(irPin3,INPUT);
  pinMode(irPin4,INPUT);
  pinMode(ledPin1,OUTPUT);
  pinMode(ledPin2,OUTPUT);
  pinMode(ledPin3,OUTPUT);
  pinMode(ledPin4,OUTPUT);
  Serial.begin(serialSpeed);
}

void loop() {
  // put your main code here, to run repeatedly:
  int reading1 = digitalRead(irPin1);
  int reading2 = digitalRead(irPin2);
  int reading3 = digitalRead(irPin3);
  int reading4 = digitalRead(irPin4);
  digitalWrite(ledPin1,reading1);
  digitalWrite(ledPin2,reading2);
  digitalWrite(ledPin3,reading3);
  digitalWrite(ledPin4,reading4);
  String output = "{\"1\":" + (String)reading1 + ",\"2\":" + (String)reading2 + ",\"3\":" + (String)reading3 + ",\"4\":" + (String)reading4 + "}";
//  String output = "{\"" + (String)reading1 + "\",\"" + (String)reading2 + "\",\"" + (String)reading3 + "\",\"" + (String)reading4 + "\"}";
  Serial.println(output);
  delay(100);
}

My Arduino circuit:
UNO 5v to breadboard 5v
UNO GND to breadboard GND
1st set: IR :5v GND
from breadboard , pin from UNO
2nd set: IR :5v GND from breadboard ,
pin from UNO
3rd set: IR :5v GND from breadboard , pin from UNO
4th
set: IR :5v GND from breadboard , pin from UNO


texts: What options do I have to wirelessly connect my computer to an arduino?

texts: For my project I have an arduino Uno connected to my robot. I need to control it wirelessly. I have thought of using a bluetooth module , but I need a larger range. Then I thought of using an RF-module like the Xbees and the 2.4 Ghz nRF24L01. However I can't use the Xbees due to budget issues. As for the nRF24L01- I understand that using the trasmitter and receiver modules I can transmit information between 2 arduinos- however I need to transmit from my computer to my remote arduino. I want to achieve this without using a second arduino at the transmitting (computer) end. Is there a way to achieve this?


texts: Atmega328p programming with Arduino libraries

texts:
I'm trying to use the serial communication to work between a naked AVR Atmega328p and a computer (OS X and Linux Ubuntu).

I can program the atmega (using a pololu programmer), I make it blink a LED on a breadboard, it works fine.

I am using the Arduino libraries to facilitate the task. And they seem to work fine (using delay, digitalRead, digitalWrite, etc).

I use a USB-to-TTL CH340 chip bought on internet. The CH340 works fine, it is recognised both on Ubuntu and OS X, and the loopback test works (Put a jumper between the TX and RX line, launch screen, type something and it comes back in the terminal), so I assume the CH340 is properly recognise and works.

Then, I plug the CH340 on my board. The 5V on the + column of the breadboard, the GND to the - column. The circuit works, my LED blinks as requested. The loop function looks like this:

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

void loop() {
  digitalWrite(9, HIGH);   // sets the LED on
  delay(30);                     // waits for a second
  digitalWrite(9, LOW);    // sets the LED off
  delay(70);                     // waits for a second
  Serial.println("loop end");
}

As you can see, at the send of the loop I send a string on the serial line. Now, I see the blue LED blinking on the USB-to-TTL converter, so it is definitely receiving data. But when I try to connect like so:

screen /dev/cu.wchusbserialfd110 9600

on OS X, or

screen /dev/ttyUSB0 9600

on Ubuntu, nothing is displayed. I just get a black terminal.

Is the Arduino Serial works with Atmega328 ? I suppose so, as it is the same microcontroller than on the Arduino. Any idea of what I am doing wrong?

Update:

More details to answer Christ Stratton question:

My low fuse is 62: 01100010. So, according to the specifications, the internal clock is used and set at 1MHz.

I programmed the Atmega using my own test bed, a Pololu programmer (as described in the book Practical AVR Microcontrollers: Games, Gadgets, and Home Automation with the Microcontroller Used in Arduino) and avrdude (through the use of platformio).
This is the command line used by platformio to flash the ROM:

/Users/[user]/.platformio/packages/tool-avrdude/avrdude -v -p atmega328p -C /Users/[user]/.platformio/packages/tool-avrdude/avrdude.conf -c avrispv2 -B 10 -e -b 115200 -P "/dev/cu.usbmodem00149121" -U flash:w:.pioenvs/pololu/firmware.hex

According to avrdude documentation, -B 10 means bitclock is set to 10us (microseconds) so a clock at speed 100Khz.

Now if I set this -B option to 1 (1Mhz), I can't program the Atmega anymore. Avrdude just timeout:

avrdude stk500v2_ReceiveMessage(): timeout


texts: My GPS coordinate does not show. Only my ultrasonic output came out

texts:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

const int trigPin = 9;
const int echoPin = 10;

long duration;
int distance;

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

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop()
{
  // This sketch displays information
  // every time a new sentence is correctly encoded.
  if (ss.available() > 0)
  {
    gps.encode(ss.read());
    if (gps.location.isUpdated())
    {
      Serial.print("Latitude= ");
      Serial.print(gps.location.lat(), 6);
      Serial.print(" Longitude= ");
      Serial.println(gps.location.lng(), 6);
    }
  }

  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance= duration*0.034/2;

  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}


texts:
I have the Arduino Pro Micro and I would like to use all the analog pins that I can on it.

It currently looks like it has a total of 9 Analog pins that can be used.

A0, A1, A2, A3, A6, A7, A8, A9 and A10.

However, I am unsure how to call these pins since all of those are also digital pins.

Would A0-A3 be defined as:

#define analog1 A0;
#define analog2 A1;
#define analog3 A2;
#define analog4 A3;

While the other pins would be this?:

#define analog5 4;
#define analog6 6;
#define analog7 8;
#define analog8 9;
#define analog9 10;

Then just call:

analogRead(analog1);
analogRead(analog2);
.....
analogRead(analog8);
analogRead(analog10);

Would that be the correct way of defining the 9 analog pins?


texts:
There are existing projects that allow the Uno and other devices using the ATmega8u2 to operate as a USB MIDI HID, such as MocoLUFA. Unfortunately, as far as I am aware, these require uploading new firmware that isn't compatible with programming via the Arduino UI.

Are there any similar projects for the ATmega32u4 (Leonardo, Micro)?

Is it possible to use an Arduino as a USB MIDI HID, while still being able to program it as normal?


texts:
I am trying to output something every one second with the following code.

volatile uint64_t timerCounts = 0;
double timenow,pretime;
void setup()
  {
     Serial.begin(19600);
     noInterrupts();
     TCCR2A = TCCR2B = 0;
     TCNT2 = 0;
     OCR2A = 124; //Zero Relative 125
     TCCR2B = B00001101;  //prescaler = 1024
     TIMSK2 |= (1 << OCIE1A);
     interrupts();

     Serial.print("Begin... \n");
  }

  //**********************************************************************
  //  Timer2 Interrupt Service is invoked by hardware Timer 2 every 0.008s
  //  16Mhz / 125 / 1024 = 125 Hz    0.008s

  ISR(TIMER2_COMPA_vect)
  {
     timerCounts++;
     if (timerCounts == 125){
        Serial.print("1s");
        timerCounts = 0;
     }
  }  // end of TIMER2_COMPA_vect

  void loop()
  {

  }

In the above code, I have set the OCR2A(output compare register) to 124``, which is well below 256(2^8). A user defined counter is also used.

However, when I execute the programme, the interval between consecutive outputs is less than 1 second.

When I change it to timer 1, the interval becomes roughly 1 second.
When I change it to timer 0, the interval becomes longer than 1 second.

Anyone knows why?

Thanks.


texts: Unable to upload to Arduino Due using version 1.6.8 of SAM tools; bossac.exe throwing an error

texts:
I can successfully see the Arduino Due when I plug it in. I can compile the code, but when I attempt to upload it to the board I get the following error:

C:\Users\user\AppData\Roaming\Arduino15\packages\arduino\tools\bossac\1.6.1-arduino/bossac.exe
        -i -d --port=COM4 -U false -e
        -w true
        -b C:\Users\user\AppData\Local\Temp\build6683778295083335366.tmp/_50key_driver.cpp.bin
        -R bossac.exe: extra arguments found
    Try 'bossac.exe -h' or 'bossac.exe --help' for more information


texts: Error with Arduino/Processing Serial Communication

texts:
I am relatively new to both Arduino and Processing and I have been working on a code that utilizes serial communication between the two. My Arduino code is reading and printing values from a piezo sensor and then sending the values to Processing, which sketches certain shapes based on the values. The code has worked previously, but for some reason it is no longer working. Everything compiles, but when I run the Processing code the sketch window is empty and remains empty. A few times the "error, disabling serialEvent()" showed up, but I just unplugged my Arduino board, closed out the programs, and restarted everything. The error no longer shows up, but my Processing sketch is still not displaying on the screen. Can someone please let me know what is wrong with my code? I really appreciate the help.

Arduino Code:

int ledPin = 13;
int knockSensor = A0;
byte val = 0;
int statePin = LOW;
int THRESHOLD = 5;
int sensorReading = 0;

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

void loop() {
 sensorReading = analogRead(knockSensor);

  if(sensorReading > 0){
   Serial.println(sensorReading, DEC);
   delay(100);
  }
}

Processing Code:

import processing.serial.*;

Serial port;

int centerX = 550;
int centerY = 400;

float val;
float ellipseX;
float ellipseY;
float ellipseW;
float ellipseH;
float ellipseXX;
float ellipseYY;
float ellipseWW;
float ellipseHH;
float lineX;
float lineY;
float lineXX;
float lineYY;

void setup(){
  background(255);
  size(1100,800);
  frameRate(10);
  smooth();

  String portname = "/dev/tty.usbmodem1411";

  //String portname = Serial.list()[0];
  port = new Serial(this, portname, 9600);
  println(Serial.list());
  //port.bufferUntil('\n');
}

void drawEllipse(float val)
{
  if(val > 0 && val < 50)
  {
    ellipseX = random(540,560);
    ellipseY = random(390,410);
    ellipseW = val + 10;
    ellipseH = val + 10;

    stroke(0);
    fill(random(255), random(200,255));
  }
}

void drawLines(float val)
{
  if(val > 50 && val < 70)
  {
    lineX = random(500, 600);
    lineY = random(360, 440);
    lineXX = random(500, 600);
    lineYY = random(360, 440);

    stroke(0);
  }
}

void drawEllipse2(float val)
{
  if(val > 70 && val < 120)
  {
    ellipseXX = random(460, 640);
    ellipseYY = random(330, 470);
    ellipseWW = val + random(20);
    ellipseHH = val + 10;

    stroke(0);
    fill(random(50, 100), random(50, 100), random(50, 100), random(220, 255));
  }
}

void serialEvent(Serial port)
{
  String inString = port.readStringUntil('\n');

  if (inString != null)
  {
      val = Float.parseFloat(inString);
  }

  drawEllipse(val);
  drawLines(val);
  drawEllipse2(val);
  println(val);
}


texts: Did I fry a Sainsmart 1602LCD (not shield, just LCD), HD44780 compatible

texts:
Each new circuit I build, I seem to make every possible mistake, including inverting 5V and ground.
I did that precise mistake on this 2x16 Sainsmart LCD. The backlight definitely works, but is the only thing I seem to be able to make work. Do you believe I fried the screen, or do they maybe have a diode to protect from erroneous cabling, and my mistake is another one?

EDIT :

I found this somewhere, on a board that might be the one driving this LCD screen or not :

Operating Voltage VDD -0.3 to +7.0 V
Driver Supply Voltage VLCD VDD - 10 to VDD + 0.3

So I mistakenly put 5V in VLCD, and 0V in VDD, which makes VLCD 5V and not 0.3V above VDD, would you suppose I fried it?

Thanks for your input :)


texts: Arduino Port randomly changes whenever I punch correct RFID tag

texts:
I was working on an Electronic Door Lock/Unlock system using Arduino Uno and RFID Reader/Tags on Ubuntu 18.04.02 lts.

Now the problem is that whenever I punch-in the correct RFID tag to the RFID reader, the Serial Monitor stops working and I notice that the "Port" value under (tools>Port) has also changed or even got un-selected.

Like, before my Port = /dev/ttyACM0

then whenever I punch in the correct tag, Port value either becomes None or gets changed to (= /dev/ttyACM1)

Also, after every 2nd or 3rd upload, I get the error message as /dev/ttyACM0: Permission Denied

My code is as follows:

#include <Servo.h>
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
#define ledPin1 A0
#define ledPin2 A1
#define Buzz A2
Servo servo;
int pos = 0;
MFRC522 rc522(SS_PIN, RST_PIN);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  SPI.begin();
  rc522.PCD_Init();     // Initialize card reader
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);
  servo.attach(3);
  servo.write(0);
  Serial.println("Scan the Card:");
}

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

  // check if any card is present and also scan only one card if multiple are present
  if(!rc522.PICC_IsNewCardPresent() || !rc522.PICC_ReadCardSerial())  return;

  // check if the type of the card is what we need and not any other card.
  MFRC522::PICC_Type type = rc522.PICC_GetType(rc522.uid.sak);
  if(type!= MFRC522::PICC_TYPE_MIFARE_MINI &&
     type!= MFRC522::PICC_TYPE_MIFARE_1K &&
     type!= MFRC522::PICC_TYPE_MIFARE_4K) return;
  String strID = "";
  for(byte i=0; i<4; i++) strID += (rc522.uid.uidByte[i] < 0x10 ? "0" : "") + String(rc522.uid.uidByte[i], HEX) + (i != 3 ? ":" : "");

  // put ID in capitals
  strID.toUpperCase();
  Serial.print("Card: ");
  Serial.println(strID);

  // Do the verification
  if(strID.indexOf("92:AA:CD:73") >=0){
    Serial.println("Access Granted");
    digitalWrite(A0, HIGH);
    tone(Buzz, 3000, 500);
    for (pos = 0; pos <= 60; pos += 1) {  // goes from 0 degrees to 60 degrees
    // in steps of 1 degree
    servo.write(pos);                // tell servo to go to position in variable 'pos'
    delay(10);                       // waits 10ms for the servo to reach the position
  }
  delay(500);
  for (pos = 60; pos >= 0; pos -= 1) {  // goes from 60 degrees to 0 degrees
    servo.write(pos);                   // tell servo to go to position in variable 'pos'
    delay(10);                          // waits 10ms for the servo to reach the position
  }
    digitalWrite(A0, LOW);
    delay(500);
  }
  else{
    Serial.println("Access Denied");
    digitalWrite(A1, HIGH);
    tone(Buzz, 300, 200);
    delay(250);
    tone(Buzz, 300, 200);
    delay(250);
    tone(Buzz, 300, 200);
    digitalWrite(A1, LOW);
    delay(400);
  }
}

Please Help!

Thanks in Advance.


texts:
I'm trying to set up a simple web-server with Arduino Yun without an SD card, i.e via REST, if I understood it right (I'm new to some of these stuff). I want to be able to "get" data (sent by Arduino) through a jQuery script and show the user a formatted HTML page.

Here I provide you a simplified version of my Arduino sketch:

#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

const byte internalLED = 13;

YunServer server;

void setup() {
  pinMode(internalLED, OUTPUT);
  digitalWrite(internalLED, HIGH);     // Turn the led on to advise about bridge begin in progress
  Bridge.begin();          // Let's activate the Yun Bridge...
  ledBlink(150);           // ...bridge activation done (user sees a blink)
  // server.listenOnLocalhost();       // Listen for incoming connection only from localhost (no one from the external network could connect)
  server.begin();          // Let's acrivate the Yun server...
  ledBlink(150);           // ...server activation done (user sees a blink)
}

void loop() {
  YunClient client = server.accept();  // Get clients coming from server
  if (client)                          // Is there a new client?
  {
    client.print(77);                  // Send a "77" to client (e.g. browser)
    client.stop();                     // Close connection and free resources.
    ledBlink(500);
  }
  delay(50);
}

void ledBlink(int delayTime) {
  digitalWrite(internalLED, HIGH); // Turn (or keep) the LED on
  delay(delayTime);
  digitalWrite(internalLED, LOW);  // Turn (or keep) the LED off
  delay(delayTime);
}

My Arduino Yun is connected via WiFi with static IP (192.168.1.98) to the same network of my laptop, and they can ping each other. Right now, if I insert into my browser the address

http://192.168.1.98/arduino/whatever

I correctly receive a simple «77» (no quotes or \r\n)

But I cannot "get" it when opening the page get_test.html (which is on my harddisk, not in the SD):

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $.get("http://192.168.1.98/arduino/whatever", {}, function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
</script>
</head>
<body></body>
</html>

This is strange to me because this html code works if I change the address inside the "get" request with https://dl.dropboxusercontent.com/u/12389503/demo_test.txt which consists only of a «21» (no \r\n). The problem is I don't even receive the alert when the address is the IP of Arduino, but the board is receiving the request since I can see the led blinking once, as expected.
I'm running out of tests, any suggestion is welcome.


texts: Arduino MEGA2560 wake up using DS3231 RTC

texts:
I am trying to set the Arduino MEGA 2560 R3 into sleep mode and wake it up with an RTC DS3231 via interrupt. I was following this tutorial:
Tutorial

One of the libraries included is the "LowPower" library, you can find it here on GitHub. It produces the following error while compiling:

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp: In member function 'void LowPowerClass::idle(period_t, adc_t, timer5_t, timer4_t, timer3_t, timer2_t, timer1_t, timer0_t, spi_t, usart3_t, usart2_t, usart1_t, usart0_t, twi_t)':

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:562:49: error: 'power_usart3_disable' was not declared in this scope

  if (usart3 == USART3_OFF) power_usart3_disable();

                                                 ^

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:597:48: error: 'power_usart3_enable' was not declared in this scope

  if (usart3 == USART3_OFF) power_usart3_enable();

                                                ^

exit status 1
Error while compiling for Arduino/Genuino Mega or Mega 2560.

I dont understand why there should be any functions in the library, which are not declared...This would mean noone could use it?! I am not an expert in C++ so maybe one of you could tell me what the issue could be. I am glad for any help.


texts: UART Software Serial - Syncing two sensors to make a tx and rx beacon

texts:
Problem

I've been trying to a create a receiver and transmitter beacon for a following robot, but have not been able to sync my two SRF02s to one another.

Any advice?

Code

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

void SendCmd(unsigned char address,unsigned char cmd)
{
  mySerial.write(address);//set the address of SRF02(factory default is 0)
  mySerial.write(cmd);//send the command to SRF02
}
void setup(void)
{
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}
void loop(void)
{
  unsigned long t3;
  unsigned long t1=micros();//time tx command issued
  SendCmd(1, 0x5C);//send pulse with transmitter
  unsigned long t2=micros();//time rx command issued
  SendCmd(2, 0x5B);//listen for pulse returns results in microsconds

 while(mySerial.available() < 2)//if two bytes were received
  {}
    t3 = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    t3 |= mySerial.read();// receive low byte as lower 8 bits
    unsigned long Tm = t3 + t2 - t1;//total amt of microseconds between pulse and reading
    unsigned long Dist = (Tm/29); //converting microseconds to cm
    Serial.print(t3); // print the reading
    Serial.println("cm");
    //Serial.print(tm);
    //Serial.println("ms");

  delay(250); // wait to read the output

}

Output#


texts: Arduino LED PWM dimmer starts blinking on low PWM values

texts:
I'm trying to build a PWM led dimmer with Arduino using this circuit:

simulate this circuit – Schematic created using CircuitLab

Everything works fine until the pin PWM 3 drops below the analog value 50 (more or less) the LEDs starts blinking fast and noticeably. However, if I touch with my finger the metal cup of the BJT transistor the LEDs do not blink anymore and they work as I assumed. The test program is below, and I've tested it with an Arduino UNO and an Arduino MEGA and they both have the same problem. The DC supplier is a transformer I bought from an electronics shop and it works properly if directly attached to the strip.

Test Program:

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

void loop(){
  for(int i = 0;i<=255;i++){
    analogWrite(3,i);
    delay( i<=40 ? 300 : 50);
  }

  for(int i = 255;i>=0;i--){
    analogWrite(3,i);
    delay( i<=40 ? 300 : 50);
  }
}

I tried searching my problem on the internet and I've found a schematic which uses a P2N2222 transistor in this article, which is equivalent to mine, except for the fact that it uses a P2N2222. I also tried changing the transistor to a new one (in case the one I'm using is broken), but it did not help.

So I don't see what I did wrong, could you please help me in finding it out?


texts: how to use keypad button multiple integer value input

texts: I have been working on water flow sensor which measures volume then i need to restrict the amount of water which disperse from depend on the user input form the keypad so how can i store the input form the keypad into a variable.


texts:
First-time poster here...

I have the following code to randomize note values and store them in an array loop1[i], where i is a specific step in the loop:

nextNote = random(-2, 3);
note = note + nextNote;

loop1[i] = note;

while (loop1[i] == loop1[i - 1] ||
       loop1[i] == loop1[i - 2] ||
       note > 6 ||
       note < 0) {
  nextNote = random(-2, 3);
  note = note + nextNote;
  loop1[i] = note;
}

(I hope this is clear enough).

Now, it usually works to a certain point until the sketch loops forever in order to randomize an allowed number. Therefore, my questions are:

Running an ATmega 2560, is this actually a task too demanding for the processor or should I suspect that it's not working properly?

How can I optimize the code, but retain the conditions above in order to avoid the loop getting stuck?


texts: Arduino ATmega328P works but board (Uno R3) seems broken

texts:
This is the first time I'm using my Arduino. It's an Arduino UNO R3. I have two boards. One works, but the other doesn't. I changed the ATmega328P from the broken one to the good one and it works, so I can confirm that the controller works. The issue seems to be in the board.

When I plug the board it doesn't come up either in Mac or in Windows. The LED blinks and the output pins have voltage, but it seems that it's only getting electricity from the computer, it's like the data channels don't respond. The other board works perfectly both on Windows and Mac.

I checked the logs on the Mac and nothing changes when I plug the board. It's like I'm not plugging anything.

Is there a way to reset the board only? Maybe a component was badly soldered in the factory. I can't use the warranty because I got the board last year and never used it until now.


texts:
I need to check if a given SSID is in range. Would be good if it didn't disconnect from the current wifi network that it's connected to, but it doesnt matter, i just need to see if a SSID is in range, whether it does disconnect or not.
It should be something like this:

if(WiFi.SSID(checkforthisSSID)) {
  //do something
}

Thanks.


texts:
So I've received few APDS-9900 sensors and found out, there's no library for it (9960 type is supported only). I took that library and device documentation, and created similar library.

Ambient light detection (without interrupts) works well, but there's trouble with proximity detection:

The "Auto-Increment protocol transaction" which should be initiated by writing (0xA0 | reg) to command register, does not work and returns two zeros instead of two bytes. See page 18 of the PDF docs (in repo).

0xE0 (Repeated Byte protocol transaction) returns at least second byte (seems so) of the ADC proximity integration result registers.

https://github.com/suculent/APDS9900_Ambient_Light_and_Proximity_Sensor


texts:
I'd like to connect about 6 contact mics to my arduino and receive simultaneous signals to be used in my computer for an art installation.

Nonetheless, I don't know what's the ideal way to go. Shall I use Analog pins or Digital? How should I connect them - what schematics shall I follow? I read that ADC is CPU intensive, but I couldn't really find any viable alternative that explicitly shows the Digital deal.

Can I connect several contact mics to different analog pins and receive their input simultaneously as shown here? If this works, then it's perfect.

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


texts: Identifying Arduino-compatible board signatures in code

texts:
I am developing libraries for compatibility across a number of Arduino/compatible boards. I know that Arduino boards can be identified by the test "#if defined (AVR_ATmega328P)" and compatibles as well: #if defined(TM4C123GH6PM).   There are a few lists of these IDs on the web but are all outdated. I have searched various cores and library code and do not see where these defines are actually defined.

Nick Gammon's Sketch to detect Atmega chip types identifies the chip type. What I'm looking for the board type to define pin configurations, etc.

Where and in what format are board signatures stored? Is there c++ code that can find the board signature? Does anyone know of a site where these signatures are stored and updated by the Arduino community?


texts: How can I sense when someone is sleeping with my Arduino?

texts:
Ignore the stalker-like title.

I am thinking about creating a project with Arduino that can sense you sleep habits, when you're asleep, and how much you sleep. It would be convenient to not have to turn it on/off at night; it should know how to do this.

Some ideas that I have:

Motion sensor
Breathing patterns (if an Arduino microphone could even pick that out... I would be surprised if it could)
A RTC clock could assist in deciding It's midnight. Usual, Steve isn't asleep at this time on Fridays. He's probably not sleeping now. It won't always be there to help you, but you might be able to try to get more accurate results this way

How can I accomplish this? (Extra points for some sort of algorithm that can tell dozing off from a deep sleep.)


texts: Pneumatic cylinders with sensors with Arduino Uno

texts:
I'm working on my own project with Arduino Uno. There are controlled 4 pneumatic cylinders via 4 coils. Every pneumatic cylinder has got their own coil which switch air to the pneumatic cylinder. Every pneumatic cylinder has got 2 magnetic sensors (when the pneumatic cylinder is retracted and extended).
I created a program for arduino but it doesn't work correctly. When I write there that I want to control only 2 pneumatic cylinders, it works correctly. If I write there the others, it skip the second if statement, do the third if statement and then do the previous if. I don't know why. The behaviour is random. What's wrong with my code? Thank you for help!

// Constants for pneumatic valves
   const int dvere = 2;
   const int davkovani = 3;
   const int lisovani = 4;
   const int vyhazovani = 5;
// ----------------------------------------
// Constants for sensors
   const int vyhazovaniZasunute = 6;
   const int vyhazovaniVysunute = 7;
   const int lisovaniVysunute = 8;
   const int lisovaniZasunute = 9;
   const int dvereZasunute = 10;
   const int dvereVysunute = 11;
   const int davkovaniVysunute = 12;
   const int davkovaniZasunute = 13;

void setup() {
  // Pneumatic cylinders set as output
  pinMode(dvere, OUTPUT);
  pinMode(davkovani, OUTPUT);
  pinMode(lisovani, OUTPUT);
  pinMode(vyhazovani, OUTPUT);

  // Sensors set as input
  pinMode(vyhazovaniZasunute, INPUT);
  pinMode(vyhazovaniVysunute, INPUT);
  pinMode(lisovaniVysunute, INPUT);
  pinMode(lisovaniZasunute, INPUT);
  pinMode(dvereZasunute, INPUT);
  pinMode(dvereVysunute, INPUT);
  pinMode(davkovaniVysunute, INPUT);
  pinMode(davkovaniZasunute, INPUT);

  // Set pneumatic cylinders as they are retracted
  digitalWrite(dvere, HIGH);
  digitalWrite(davkovani, HIGH);
  digitalWrite(lisovani, HIGH);
  digitalWrite(vyhazovani, HIGH);
}

void loop() {

  if(digitalRead(dvereZasunute) == HIGH)
  {
      digitalWrite(dvere, LOW);      // extend the first pneumatic cylinder when the sensor is lighted on because the pneumatic cylinder is retracted
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
  )
  {
      digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
      delay(4000);
      digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
      // this code works when it is alone there, the next if statements not
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(lisovani, LOW);    // extend the third pneumatic cylinder
      delay(3000);
      digitalWrite(lisovani, HIGH);   // retract the secondthird pneumatic cylinder after 3 seconds
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(dvere, HIGH);      // retract the first pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH && digitalRead(vyhazovaniZasunute) == HIGH)
  {
      digitalWrite(vyhazovani, LOW);    // extend the fourth pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH&& digitalRead(vyhazovaniVysunute) == HIGH)
  {
      digitalWrite(vyhazovani, HIGH);    // retract the fourth pneumatic cylinder
  }

  // sensors - HIGH - light on, LOW - light off,
  // pneumatic cylinders - HIGH - retracted, LOW - extended.
}


texts:
I want to send DMX with my Arduino Mega 2560. I'm using the IDE 1.6.7

I tried the AVR -> DMX source code from Ulrich Radig and also the layout for the RS-485 transmission.

I modified the code to fit the ATMega2560 but when I upload the code nothing happens.

The only thing I didn't do is to use the 22 Ohm resistors, is that a problem?

Any idea?

Here is my circuit:

Here is the source

#include <avr/interrupt.h>
#include <avr/io.h>
#include <stdio.h>

#define F_CPU 16000000
#include <util/delay.h>

#define DMX_BAUD 250000
#define DMX_BAUD_BREAK 80000
#define DMX_BAUD_BREAK_UBBR ((F_CPU+DMX_BAUD_BREAK*8)/(DMX_BAUD_BREAK*16)-1)
#define DMX_BAUD_UBBR ((F_CPU+DMX_BAUD*8)/(DMX_BAUD*16)-1)

volatile unsigned char dmx_buffer[512];

//############################################################################
//DMX Senderoutine
ISR (USART_TX_vect)
//############################################################################
{
  static unsigned int  dmx_channel_tx_count = 0;
  static unsigned char dmx_tx_state = 0;

  switch (dmx_tx_state)
  {
    case (0):
      UBRR0   = DMX_BAUD_BREAK_UBBR;
      UDR0 = 0; //RESET Frame
      dmx_tx_state = 1;
      break;

    case (1):
      UBRR0   = DMX_BAUD_UBBR;
      UDR0 = 0; //Start Byte
      dmx_tx_state = 2;
      break;

    case (2):
      _delay_us(10);
      //Ausgabe des Zeichens
      UDR0 = dmx_buffer[dmx_channel_tx_count];
      dmx_channel_tx_count++;

      if(dmx_channel_tx_count == 512)
      {
        dmx_channel_tx_count = 0;
        dmx_tx_state = 0;
      }
      break;
  }
}

void setup() {
 //Init usart DMX-BUS
 UBRR0   = DMX_BAUD_UBBR;
  DDRE |= (1<<PE1); //Output TXD Pin ATmega2560
  UCSR0B|=(1<<TXEN0)|(1<<TXCIE0); // TXEN0 Transmitter enable / TXCIE0 TX complete interrupt enable
  UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
  sei();//Globale Interrupts Enable
  UDR0 = 0;//Start DMX

}

void loop() {
  // put your main code here, to run repeatedly:
    dmx_buffer[4]=255;
    _delay_ms(1000);
    dmx_buffer[5]=255;
     _delay_ms(1000);
    dmx_buffer[6]=255;
    _delay_ms(1000);
    dmx_buffer[4]=0;
    _delay_ms(1000);
    dmx_buffer[5]=0;
     _delay_ms(1000);
    dmx_buffer[6]=0;
     _delay_ms(1000);

}


texts: Can I compile a sketch for my attiny85 without an arduino board?

texts:
I have a lot of Raspberry Pi's laying around, so I want to use those to program my attiny85 chips. The problem is that most of the code examples, libraries, and documentation out there assume you're using Arduino. Can I run Arduino commandline software on my Raspberry Pi, and use that to program the attiny85?

I'm trying to compile an RF24 program for the attiny using avr-g++, but I'm running into too many dependency errors, and I wonder if things will just be easier if I use Arduino software.`


texts: Disable Reset when Com Port Connected/Disconnected

texts: I've noticed that when I open and close the com port my Arduino is connected to, the device resets. This makes the program run the setup profile again and it loses the previous variable states. Is there any way to prevent this?


texts: ATtiny Mapping PPM Inputs to Move Servo Issue

texts:
Short Version:
Not able to get a servo to move to mapped input from RC remote control PPM signal.

Detailed Verison:
I am trying to take an input signal from a hobby RC radio (D4RII receiver ppm stream/one wire) signal and map the values 1000-2000 into 0-180 for a value that is useful for a servo. Initially, I had an issue simply reading the values stored within the array from the TinyPpmReader.h library from DigisparkArduinoIntegration on github.

For background, I am using tiny cores. This was the fist issue that was solved:
Accessing Values From Array Within a Library

Second Issue solved:
Mapping PPM Signals to Servo Values

Now, the last part of the battle is to get the servos the actually move. I have successfully (with help)

1.Made the single array values available to be read via serial console (Uno to ATtiny85) like this - Serial.println(TinyPpmReader.width_us(3));

2.Successfully mapped the values within the ppm array to 0-180 and validated the values are correctly mapped and printed to the serial console like this - Serial.println(mappedval0);

Couple of questions. Is it possible that since the ATtiny 85 only has Timer0 and Timer1 available that pwm wont work? ATtiny 85 datasheet here.  If I understand it correctly, the tinyppmreader library does use an interupt driven process.

I chose to go with the SoftwareSerial library since I don't think it is using any timers (Not really sure).  Or, is this just a simple coding issue? What is my mistake? This will compile and the servo does seem to glitch around but not move according to the mapped ppm stream.

Since my search results are now coming up with my previous questions I am hoping this will help others be able to use ppm / servos with the ATiny 85 since it is so small and perfect for many RC related projects.

CODE:

#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>
#include <SoftwareServo.h>
//#include <TinyServo.h>

int val0;                    // integer to store value
int mappedval0;
#define PPM_INPUT_PIN  4

SoftwareServo myservo;

const int PPM_max_value = 2000; //put the max value of PPM reading result
const int PPM_min_value = 980; //put the min value of PPM reading result

//const byte SERVOS = 1; // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
//const byte servoPin[SERVOS] = { 1 }; // what pins are your servos on?
// you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

//#define RIGHTLEGSERVO 0

void setup()
{
  Serial.begin(38400);//attiny tx - rx uno does not work at 9600 baud. Set to 38400 @ attiny 1mhz and uno serial console to 38400 baud
  TinyPpmReader.attach(PPM_INPUT_PIN); /* Attach TinyPpmReader to PPM_INPUT_PIN pin */
  //setupServos();
    myservo.attach(0);
}

void loop()
{
   val0 =TinyPpmReader.width_us(3);   //get PPM reading result from index 4
   mappedval0= map(val0, PPM_min_value, PPM_max_value, 0, 180);
   myservo.write(mappedval0);
   //moveServo(RIGHTLEGSERVO, mappedval0);
   //Serial.println(mappedval0);
   SoftwareServo::refresh();
   delay(50);

}

I have commented out the tinyservo library parts while testing the SoftwareServo library.


texts: is any windows application available for accelerometer based computer mouse

texts: I want to make an AIR mouse using Arduino and accelerometer, for this i used USB to TTL converter i have done everything successfully but can anyone tell me how use it in computer. I mean i don't know how to make computer application for this mouse. please suggest me any application for this. And give any idea for "how can i use Bluetooth for this."


texts:
I plan to do the following:

void setup(){
  String term = "12 + (2 * 5)";
  int result = eval(term); // eval function (from Python)
  Serial.println(result); // expecting 22
}

However there is no eval function. Are there any alternatives?


texts:
I'm trying to DIY about a dozen BlinkSticks (discontinued, Adafruit) pictured here

I'm thinking to use a Digispark ATTINY85 to control a single RGB LED to show the status of some program running under Linux. Here is the proto board I have my eye on:

I could either use a single individually addressable RGB LED with a built-in WS281X controller

or a plain RGB LED with each color pin connected to a GPIO pin on the TINY85.

This is my first Arduino project, so I'm not familiar with the best way to approach this project. I'm trying to keep the part count low as well so the serial data approach is appealing too. Has anyone done this before and can explain their setup?

Prior work I've found for the simple control approach:


texts: Genuino 101 - Can't upload my sketch - Timeout Error

texts:
I'm trying to run a sample sketch on my Genuino 101 but the following error shows up. Here is a verbose version.

Starting download script...
Args to shell: [/home/userk/.arduino15/packages/Intel/tools/arduino101load/1.6.9+1.28/x86/bin /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin /dev/ttyACM0 verbose ATP1BLE000-1541C5635 141312]
Serial Port: /dev/ttyACM0
BIN FILE /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Flashing is taking longer than expected
Try pressing MASTER_RESET button
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
ERROR: Timed out waiting for Arduino 101 on /dev/ttyACM0

I have installed the Intel Curie package with the Boards Manager and tried to press the Master Reset button, the reset and a combination of both. Nothing.

I have also tried the suggestions provided in this question but they did not work. I am using Ubuntu 16.04. Do you have any advice?

EDIT: Same problem with Windows 10/8/7.


texts:
So I am programming an LED Music Visualizer that uses a combination of Processing and Arduino. I have it all working as I want to but there is a small problem. If I were to stop the music, then the Arduino will keep displaying the visualization for a few seconds. I believe that this issue would be caused by it "catching up" on new serial data from Processing like a queue. So my question is: When arduino uses the Serial.read() function, is it using the most recent value or is it using the next value received after the last one that it used, like a queue of values.

Example: Processing sends the values 1,2,3,4,5,6,7,8,9 over serial in 10 millisecond intervals. Arduino only performs Serial.read at 20 millisecond intervals. Would the arduino read the values 1,3,5,7,9 in or would it read the values 1-9 but in twice the time?

Sorry for the confusing question, hopefully somebody could shed some light. At the core, it is a question on how serial works, you can ignore the part about the music visualizer.


texts: How to access Attiny84 port B in Arduino IDE code?

texts:
Referring to guide at High-low tech, I were able to flash ATTiny84 via UNO through Arduino IDE 1.6.7.

I loaded a simple blink LED program on IDE pin 0 (physical Attiny84 pin 13, PA0) and everything works fine for pin 0 till 7 at Port A.

But what if I want to access or blink a LED at one of the pins at Port B? Example, PB0 (physical pin 2)

The following is my current code to blink PA7

int led=7; //PA7

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

void loop() {
  digitalWrite(led, HIGH);
  delay(100);
  digitalWrite(led,LOW);
  delay(100);
}


texts:
I want to check my understanding on how to use digitalWrite for 5V and Grd and why this code isn't working.
This is for the Makeblock sensor
Consider the image here which says to plugin a wire to 5V, Grd and a signal pin.
My code does the following
#define h  22
#define l  24
#define sig 26

void setup() {
   Serial.begin(9600);
   pinModde(h, OUTPUT);
   pindMode(l, OUPUT);
   pinMode(sig, OUPUT);

   digitalWrite(h, HIGH);
   digitalWrite(l, LOW);
}

void loop() {
   digitalWrite(sig, LOW);
   delayMicroseconds(2);
   digitalWrite(sig, HIGH);
   delayMicroseconds(10);
   digitalWrite(sig, LOW);
   pinMode(sig, INPUT);
   long duration = pulseIn(sig, HIGH, 38000);
   delay(2500);
}

When I run this code duration is always 0.  If I unplug 22 and 24 and use the board's 5V and Grd I get duration is 30001 no matter how far away an object is from the sensor.  Meaning it's not sensing anything, just returning this number.
Full disclosure that I'm using solder-less wires but I don't that would make this much of a difference?
So to summarize: why are 22 and 24 resulting in a 0 readout and not acting as 5V and Grd?  My only thought is maybe too much voltage and a resister is needed?
Secondly: why is the sensor not working even when using 5V and Grd pins?


texts: Merge two 8 bit arrays to one 16 bit array

texts:
I am an absolute newbie to Arduino and C++ and try to go through some tutorials to gain a minimal insight. However I stuck already at some tiny Points. What I want to do? Merge two 8 bit integer Arrays in to one 16 bit Array:

int summand_one[8] = {0,0,0,1,1,0,0,0};
int summand_two[8] = {1,0,0,0,0,0,0,1};

int * summand = new int[16];
std::copy(summand_one, summand_one+8, summand);
std::copy(summand_two, summand_two+8, summand+8);

The result should be

{0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1}

However it's not working at all. Constructor/destructor/type errors…

Any helpful idea how to do this?


texts: How to connect multiple MPU-9250 IMU sensors to a single Arduino Uno?

texts:
The datasheet says the I2C bus limits itself to only two MPU-9250 sensors. How can I control multiple (>2) MPU-9250 through a single Arduino Uno? Is it possible to add another bus?
Please, help.


texts: Automatic water pump Trigger System - I need my code FIXED

texts:
int out = LED_BUILTIN;
int strt = 3;
int stp = 9;
void setup() {
  pinMode(out,OUTPUT);
  pinMode(strt,INPUT);
  pinMode(stp,INPUT);
}

void loop() {
  while(true) {
    if(digitalRead(strt) == LOW) {
      digitalWrite(out,HIGH);
      delay(1000);
    }
    if(digitalRead(stp) == HIGH) {
      digitalWrite(out, LOW);
      delay(1000);
    }
  }
}

I'm a beginner so I believe someone would help me out. Actually the mechanism I'm using for turning the state of Pin 3 & 9 is through 3 wires connected to the Pins D3,D9 & 5V in the nano board. Where 5 V is immersed in water and Pin 3 does not touch water Nano's Built in LED is turned on and if the water reaches Pin 9 (while the Pin 3 wire is still submerged under water) the LED goes Off.
In the above code, the Built in LED turns High just fine if Input Pin 3 Reads Low. Although as soon as Pin 3 goes High the LED turns Low and does not wait for Reading input pin 9 which is when the LED should actually turn Off.
In the first IF Clause (For Reading Pin 3(strt) to LOW) I want that part of the code to only set the OUTPUT pin LED_BUILTIN to be set to HIGH & not revert back to LOW if pin 3 is turned to HIGH. But only if the INPUT pin 9 in the second IF Clause reads HIGH then only should the OUTPUT Pin LED_BUILTIN be set to LOW.
Thank You for the helping hand.
This is the Link for the Code that I used(I Modified the code to have two input Wires) : https://www.instructables.com/Water-Level-Alarm-Using-Arduino/


texts:
I am planning to build a LED polar clock, so it will need about 181 LEDs (12 Month, 31 Day, 7 Day-of-week, 12 Hour, 60 Minute, 59 Second) and I need to control each one individually. I will be buying everything from scratch so I ask for help on:

Which arduino to use
How to make it keep time
How to control the LEDs

The LEDs need to stay on once they're lit, e.g. at 5 o'clock, the 1-5 LEDs would be on.
This is why I don't know that multiplexing or charlieplexing will work, as I read that it is better if the LEDs wont be remaining on/only a few are on. The most that could be on is 179 (Friday, December 31, 11:59:59 [Won't happen until 2021]).

Thanks in advance.


texts: I2C comunication, ESP->Nano on endTransmission no ACK fron nano

texts:
i am trying to communicate between ESP(master) and arduino nano(slave). This is only a prototype and all works fine. But i want to  add multiple arduinos and therefor i need to detect if the arduino is connected.
I use the return function from wire.endTransmission as shown in i2c scanner to detect devices. But it doesnt work.
On the arduino i have this program:
#include <Wire.h>

const int16_t I2C_SLAVE = 0x22; // 0x22 = 34 cize izba 3(30)

void setup() {
  Wire.begin(I2C_SLAVE);

}

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

}

on the ESP i am trying this:
Wire.beginTransmission(I2C_adress[adress]);
int error = Wire.endTransmission();

Serial.println(error);

It returns only 2 (received NACK on transmit of address)
Why? When i have other code on the slave (with onRecive and onRequest all works and comunicates)
Thank you.


texts: Receiving message from arduino through wifi

texts: I am new to arduino . I went through the basics . I want to receive message from arduino uno r3 in my laptop(ubuntu) . I have esp8266 wifi module . Arduino and esp8266 connection done . How do I proceed further ?


texts: How to add Attiny13 to Attiny board profile in Arduino IDE 1.6?

texts:
Several months ago, I asked how to add (or where to get) Attiny13 to the list of boards in the Attiny package available in github: https://github.com/damellis/attiny In post 1.5 IDE, the package is installed by adding repo's JSON file to boards manager, as described in this post: https://arduino.stackexchange.com/a/23056/2955

Nowhere it says how to modify the files, not at all. And the package doesnot contain Attiny13 info.

The answer to my question was to do it myself and make a pull request. So ok, but how do I do it? I don't understand those files. The JSON file refferences some SHA-256 named zip files. That's hardly something that can be clearly and simply edited.

Can anyone tell me clearly what do I have to do to get Attiny13 working within that profile?


texts: How get assembler/preprocessed code for library

texts:
I am using https://github.com/sudar/Arduino-Makefile project with https://github.com/ladislas/Bare-Arduino-Project to compile my Arduino projects from Linux command line. I put as much as possible functionality to libraries for reuse (and use the same libraries from many projects too).

Now I had run to some problems and I am not sure, if I am using the language (C/wiring/...) properly, as a lot of #define macros are used. I think, that seeing the resulting code would help me greeatly in finding, wheather some specific lines are compiled into what I want them to be compiled. I am interested mainly in the library code, even if it would mean to dump full program together with all used standard libraries. (I can find my way in large files.)

I would prefere intermediate files, as I suppose they could contain more info than just dissassembled .HEX file, but if this assumption is not correct, and I can get the same from .HEX, than I can use that way as well.

Question: How to get intermediate files (Ideally both "plain C" after preprocessing all macros AND "plain ASM" after compiling the code) ideally with corresponding lines of original code as comments inside.

Subquestion: In the above, how to disable optimalisation as much as possible, to get the code more verbatim similar to original C (I know, that it would hurt both speed and size and I do not care - I just want to be sure compiler does undertand my code the same way as I myself and if not, then see, where I made mistakes)

Thanks for all suggestions :)


texts:
Hi guys I am new to this language and i just tested the code to control a servo motor
Can anybody help me please ? here is the code

void setup() {

  servo_test.attach(3);
  pinMode(9, INPUT);

}

void loop() {

 if ( digitalRead (9 == HIGH)) {

   for(angle = 0; angle < 180; angle += 5)    to 180 degrees
  {
    servo_test.write(angle);
    delay(5);
  }

  delay(4000);
  for(angle = 180; angle>=1; angle-=5)      to 0 degrees
  {
    servo_test.write(angle);               specified angle
    delay(5);
  }

    delay(4000);
}

}

It is just like the arduino completely ignore the if statement and start the loop wheter pin 9 is in high or low state  even if  i wire it directly to gnd


texts: How do I choose proper diodes for a 74HC595 shift register with a wired OR connection?

texts:
I want to use a wired OR connection to connect some pins of the 74HC595 shift register to an Arduino Digital Input Pin. How do I choose proper diodes for this situation?

Maximum rated forward current has to be higher than whatever current a single pin of the 74HC595 produces.
The V_F forward voltage drop has to be as low as possible to make sure that a HIGH from the shift register has still a voltage high enough to result in a HIGH at the Arduino pin after passing through the diode.
Switching time has to be low enough to match the shift register's frequency.

So far, so good? What did I miss?

By the way, I haven't decided on the voltage for VCC, yet. Most likely, either 5 V or 3.3 V.


texts:
This code It works in atmel studio.But this millis function is starting to run 31-34 miliseconds behind of arduino millis fuction.Why?I am adding picture.

Picture: https://imageshack.com/a/img922/3060/umtNJp.jpg

Update 2

#define F_CPU 8000000UL
#include <avr/io.h>

#include <avr/interrupt.h>

#define clockCyclesToMicroseconds(a) ( ((a) * 1000L) / (F_CPU / 1000L) )
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
// the fractional number of milliseconds per timer0 overflow. we shift right
// by three to fit these numbers into a byte. (for the clock speeds we care
// about - 8 and 16 MHz - this doesn't lose precision.)
#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
#define FRACT_MAX (1000 >> 3)
volatile unsigned long timer0_overflow_count = 0;
volatile unsigned long timer0_millis = 0;
static unsigned char timer0_fract = 0;

volatile uint8_t count;

ISR (TIMER0_OVF_vect)

{

    unsigned long m = timer0_millis;
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
    }

    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

}

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
    m = timer0_millis;
    SREG = oldSREG;

    return m;
}

int main (void)

{
    DDRB |= (1<<0);
    TCNT0 = 0;
    count = 0;
    TCCR0B |= (0<<CS02) | (1<<CS01) | (1<<CS00); // PRESCALER 64
    TIMSK0 = (1<<TOIE0);
    sei();

    while(1)
    {
        millis() to uart.

    }

}


texts: Modify the call stack of interrupts on Arduino

texts:
I'm working with Arduino's libraries. And my interest in the possibility to change the call stack of the SPI interrupt, this because I want: after the interrupt happen, the program could jump to other function and not to the interrupted address.

I mean:
This is the Main code.

void loop ()
{
    func();
}

void func()
{
   // code
   // here happens the ISR interrupt
}

ISR happens inside func()

ISR(SPI_STC_vect)
{
    // code
    // SPDR = 0x00; // MY ANSWER to SPI
    // MODIFY CALL STACK TO GO TO LOOP()
}

Now, after answering the SPI, I want to go back to loop() instead of continue func().

How can I do this?

Thanks for your help.


texts:
I have a setup that controls the rotation of two stepper motor using Arduino UNO, HBS860H stepper drivers, 4X4 keypad and LCD screen. I have replaced the Arduino Uno by a Controllino Mega and it works good. Now I am trying to replace the Keypad and LCD screen by a FATEK HMI PN2043NK.
I have the sketch for the Controllino,
I can use RS485 to communicate both devices.
I use FV Designer to program the HMI, but I don't understand how to run the sketch from the HMI.
I need some help with a simple example Please, any help I could use to start learning to communicate the HMI with the Controllino and run the steppers will be welcome.


texts: Control Speed of DC FAN Using Arduino PID Library

texts:
I want to make a circuit that control speed of DC fan Using Arduino PID Library to get thing at specific temperature.

The circuit looks like this but can be changed, The dc fan motor connected to PWM 3 and thermistor connected with pin A0.

The thermistor check the temperature of a device that heated by nearby heater so fan cools the device to get the specific temperature.

Case 1

When Heater not running, the thermistor value in Serial monitor 0-1023, When fan not running it gives 1023 and when fan runs at full speed it gives about 0.

Case 2

But when heater is running the values of thermistor has been changed and when fan not running it gives 1023 and when fan runs at full speed it gives about 500.

I want to set a point 650 from thermistor value(INPUT Value), and fan speed have to adjust using pid so temperature adjusted and the thermistor gives 650 value.

Sample PID code

 #include <PID_v1.h>
//Define Variables we'll be connecting to double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);
void setup()
{
  Serial.begin(115200);
  //initialize the variables we're linked to
  Input = map(analogRead(0), 0, 1023, 255, 0);
  Setpoint = 650;
  myPID.SetOutputLimits(0, 255);
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}
void loop()
{
  int sensorValue = analogRead(0);
  Input = map(analogRead(0), 0, 1023, 255, 0);
    double gap = abs(Setpoint-Input); //distance away from setpoint
  if(gap<10)
  {  //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
     //we're far from setpoint, use aggressive tuning parameters
     myPID.SetTunings(aggKp, aggKi, aggKd);
  }
  myPID.Compute();
  analogWrite(3,Output);
  Serial.println(sensorValue);
}

What changes have to done in code so we can set point from input values?
And
Please help me so this code works for me.


texts: Arduino how can I search for missing library header files

texts: How can I search for blank library header files (ie. .h files).


texts: I want to connect sim800l module with arduino pro mini, I don't find any circuit diagram or tutorial for this. I want a circuit diagram for this.


texts: C++ Namespace/scope problem when trying to attach arduino interrupt

texts:
I have defined a c++ class (RpmDriver) and want to use attachInterrupt in the constructor to link an Arduino pin to its ISR (RpmInt) in the class. When I try this, I get:

error: cannot convert 'RpmDriver::RPMInt' from type 'void (RpmDriver::)()' to type 'void (*)()'

This is the cpp file:

#include "RpmDriver.h"
#include <Arduino.h>
int currentRpm;
long lastMillis;
int pin;

RpmDriver::RpmDriver(int Pins[])
{
    pin=Pins[0];
    currentRpm=0;
    pinMode(pin,INPUT);
    lastMillis = millis();
    attachInterrupt(digitalPinToInterrupt(pin),RPMInt, RISING);
}
RpmDriver::~RpmDriver(void)
{}

bool RpmDriver::GetData(char* dest,char* format)
{
    sprintf(dest,format,currentRpm);
}

void RpmDriver::RPMInt()
{
    double RPMConstant=40000;
    unsigned long newMillis=millis();
    unsigned long t = newMillis-lastMillis;
    t=100;//temp
    currentRpm=(t==0)?0:(int)RPMConstant/t;
    lastMillis=newMillis;
}

and the header file is

#pragma once
class RpmDriver
{
public:
    RpmDriver(int pins[]);
    ~RpmDriver(void);
    bool GetData(char*,char*);
private:
    void RPMInt(void);
};

Any help much appreciated!


texts: Can't read data from registers using I2C

texts:
I am trying to read data from the registers 6, 7, 8 and 9 of the STC3100 (Data Sheet) using an arduino uno.
I followed this tutorial: https://howtomechatronics.com/tutorials/arduino/how-i2c-communication-works-and-how-to-use-it-with-arduino/ And adjusted the device and register adress accordingly.
This isn't working and instead of returning the data on the register I'm just getting 16 over and over again.
Here is my code:
#include <Wire.h>
int ADXLAddress = 0x70;

#define X_Axis_Register_DATAX0 0x08

#define X_Axis_Register_DATAX1 0x09

#define Power_Register 0x00

int X0,X1,X_out;

void setup() {

  Wire.begin();

  Serial.begin(9600);
  delay(100);
  Wire.beginTransmission(ADXLAddress);
  Wire.write(Power_Register);
  Wire.write(16);
  Wire.endTransmission();
}
void loop() {
  delay(2000);
  Wire.beginTransmission(ADXLAddress);

  Wire.write(X_Axis_Register_DATAX0);
  Wire.write(X_Axis_Register_DATAX1);

  Wire.endTransmission();

  Wire.requestFrom(ADXLAddress,2);

  if(Wire.available()<=2) {
    X0 = Wire.read();
    X1 = Wire.read();
  }

  Serial.print("X0= ");
  Serial.print(X0, BIN);
  Serial.print("   X1= ");
  Serial.println(X1, BIN);
}


texts:
I am new in Arduino but I have experience in electronics.

I was wondering how can I make a countdown timer using a CD4510 and an Arduino UNO. I know you would suggest that I should connect my seven segment display on the IO pins but I can't do that because I will use multiple seven segment displays.


texts: How to measure total energy usage of an arduino board

texts:
I have a project that I'm currently working on. We have built a green wall, wich consists of plants on a wall

Now, we have a pump situated at the bottom that waters all the plants. There is an arduino board that decides when to put the pump on. Powering it is a solar panel and wind turbine. We want to know how much energy we have saved by using the solar panel and turbine.

Question:

How do I measure the amount of energy, in Wh, used from 00h00 that day? Is there a library? Or is this not possible with Arduino?

Thanks a lot.

To clear up some things

No, the pump is not fueled directly by the Arduino pin. We are using a motor shield.

Yes, there is an accumulator in the circuit. The solar and wind power recharge a battery which in turn powers the components.

I would like to know the entire energy consumed, not just the pump.


texts: How do I see underlying code and definitions inside Arduino IDE on MacOS X El Capitan

texts:
I'm a newbie to Arduino so please excuse the easy question and guide me to the appropriate sources or forums.  I just bought an Arduino Uno Starter Kit that comes with the "Arduino Projects Book" by Scott Fitzgerald et al and I'm happily working my way through the projects.  I downloaded the Arduino IDE (version 1.7.10) onto my mac and am turning on lights, etc.  However, I'd like to see the underlying code.  For example, I use the code "digitalWrite" to turn off/on LEDs.  I'd like to see the code for this.  I can imagine that it's just a write of 1 or 0 to a particular memory address, but I'd still like to see it.  I was hoping there was a right-click->"Go To Definition", but I don't see it. I downloaded the Arduino IDE to my Downloads folder and run it just from there. It's called Arduino.app.   I don't see a folder with .c and .h files as suggested in this post:  Arduino IDE, Underlying Code and Libraries  Maybe I'm missing them?

Also, is it possible to set a breakpoint?

Again, sorry if these are "obvious" questions.  And I did look at the Arduino site without any success.

Thanks,

Dave


texts: Are there better options for Iridium satellite communications?

texts:
Recently I've gotten interested in radio communications, I'd really like to use the RockBlock module but it's pretty expensive. Does anyone know of some cheaper options that work with Arduino?
Here's the link to the RockBlock
https://www.rock7.com/shop-product-detail?productId=51


texts: how to make an led turn on when something gets close to an ultrasonic sensor

texts:
Hey I just started using arduino and so far can't get any help with how to write a code for an led to turn on when someone gets in range of a three pin ultrasonic sensor, and off when they are out of a specific range.

Any help?


texts: Why does Arduino round off some integers but not others when my desktop PC does not do this?

texts:
I am writing (in C) some low level digit manipulation routines that convert int to float and vice versa for Arduino. I came across some puzzling behaviour with Arduino rounding some numbers but not others. So I located and extracted the offending code into a simple program which I compiled on desktop Linux PC with GCC and on Arduino - they give different results. Why?
Here are the programs. The goal is to take the float number 1.3140 and the float number 2.3140 and split them into two integers. In the first case I expect '1' and '3140' and in the second case I expect '2' and '3140' (the terminal '0' is important for my application).
The Arduino code:
void setup() {
double dnum,x,y;
uint16_t intpart,fracpart;

Serial.begin(9600);

dnum = 1.3140;

 x=modf(dnum,&y);
 intpart = (uint16_t)y;
 fracpart = (uint16_t)(10000.0*x);

Serial.println(dnum,4);
Serial.println(intpart);
Serial.println(fracpart);

}

and the output I get is:
1.3140
1
3140

Fantastic! Success. But hold on. If I change the hard-coded number to dnum = 2.3140 I get this:
2.3140
2
3139

What? Why did it round the second part down? Am I doing something fundamentally wrong? So I wrote a little C program for my PC (compiled with gcc). Here is the code:
#include<stdint.h>
#include<stdio.h>
#include<math.h>

int main (int argc, char *argv[])
{
 double dnum,x,y;
 uint16_t intpart,fracpart;

 dnum = 2.3140;

  x=modf(dnum,&y);
  intpart = (uint16_t)y;
  fracpart = (uint16_t)(10000.0*x);

 printf("Int_part = %u\nFrac_Part = %u\n",intpart,fracpart);

 return 0;
}

When run I get this result:
Int_part = 2
Frac_Part = 3140

Now that's what I expect - and to be thorough I also did the above C program with dnum = 1.3140; and I again got the 'correct' expected result:
Int_part = 1
Frac_Part = 3140

So why does the Arduino round the fractional part down when I convert it to an integer sometimes and not others?
I tried this on a genuine Arduino Uno, a clone Arduino uno and a clone Arduino nano and all give the same results. In 'theory' it could be some difference in the compiler tolerance to some coding impropriety I have done (gcc is more tolerant) but can anyone tell me what I did wrong and how to get the Arduino to behave (the way I want it to)? Thanks.


texts:
I'm trying to create an array of objects and later iterate over it and do something with each object. My C++ skills just don't go far enough.

Here's what I have so far. I've tried to strip out all the meaningless code. Whats wrong is my tr object is not what I expect it to be. It's numOfCars property is 0 so I know I'm not accessing the train object that I expected.

#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {
    //code intentionally removed
}

void Train::move() {
    //code intentionally removed
}

const int trainCount = 2;
Train train1;
Train train2;
Train trains[trainCount] {train1, train2};

void setup() {
    Serial.begin(9600);
    train1.numOfCars = 5;
    train1.init();

    train2.numOfCars = 5;
    train2.init();
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Train tr = trains[n];
        Serial.println(tr.numOfCars); //always prints 0
        tr.move();
    }
}


texts: Why isn't this pushbutton program working?

texts:
Here is my circuit:

and here is my code:

int LED = 13;
int BTN = 7;

void setup() {
pinMode(LED,OUTPUT);
pinMode(BTN,INPUT);
}
void loop() {
if(digitalRead(BTN) == HIGH) {
digitalWrite(LED,LOW);
}
else{
digitalWrite(LED,HIGH);
}
}

When I press the button, the LED is supposed to go low, but it doesn't. What is wrong with this circuit/code?


texts: How to read a higher voltage digital input?

texts:
Lets suppose I have a circuit with a car battery, a switch and a led. The led will turn on when the switch is closed, and turn off if it's not. I want to remove the led from the circuit and put an Arduino in that place to "read" when the circuit is closed or open.

I'm a good programmer, so the code is not the real problem. I only want to know how to do this without damaging the board.

How can I do this?


texts: How to enable exception handling on the Arduino Due?

texts:
While the question here gives some hints, the solution provided there does not directly work on the Due, since it uses a different compiler and toolkit. Also, the Due has more than enough flash for most projects, so that the extra code required for exception handling is acceptable. But as with the AVR-based boards, "-fno-exceptions" is automatically added to the compiler flags when using the Arduino IDE, preventing any throw or catch instructions to compile.
How can I enable exception support on the Due?


texts: Arduino pin 3 to 7 used in serial data transfering

texts:
Good day.

I am new in Arduino so please bear with me. I need to know if Pins other than Pin 0 and 1 can be used as a serial connection. I have 3 devices that needs to be connected to Arduino via USB, but when I saw the specification of Arduino, it only implicate that only pins 0 and 1 is used for serial rx/tx. So is it possible to connect the other 2 usb connector via pin 2 to pin 5

Thank you very much for your answer