Posts with «serial» label

Quick Arduino Hack Lets Tach-less Car Display Shift Points

A tachometer used to be an accessory added to the dash of only the sportiest of cars, but now they’re pretty much standard equipment on everything from sleek coupes to the family truckster. If your daily driver was born without a tach, fear not – a simple Arduino tachometer is well within your reach.

The tach-less vehicle in question is [deepsyx]’s Opel Astra, which from the video below seems to have the pep and manual transmission that would make a tach especially useful. Eschewing the traditional analog meter display or even a digital readout, [deepsyx] opted to indicate shift points with four LEDs mounted to a scrap of old credit card. The first LED lights at 4000 RPM, with subsequent LEDs coming on at each 500 RPM increase beyond that. At 5800 RPM, all the LEDs blink as a redline warning.  [Deepsyx] even provides a serial output of the smoothed RPM value, so logging of RPM data is a possible future enhancement.

The project is sensing engine speed using the coil trigger signal – a signal sent from the Engine Control Unit (ECU) which tells one of the ignition coilpacks to fire. The high voltage signal from the coilpack passes on to the spark plug, which ignites the air-fuel mixture in that cylinder. This is a good way to determine engine RPM without mechanical modifications to the car. Just make sure you modify the code for the correct number of cylinders in your vehicle.

Simple, cheap, effective – even if it is more of a shift point indicator than true tachometer, it gets the job done. But if you’re looking for a more traditional display and have a more recent vintage car, this sweeping LED tachometer might suit you more.

[via r/Arduino]


Filed under: Arduino Hacks, transportation hacks

Monitor A Serial Port From Anywhere

This simple WiFi serial port monitor would have saved us a lot of trouble. We can’t count how many times where being hooked into an Arduino with USB just to get the serial out has nearly been more trouble than it’s worth. Times where we sat cross-legged on the floor and could choose comfort or accidentally shifting the set-up and ruining everything, but not both.

[Frenky]’s set-up is simple and clever. The Ardunio’s serial out is hooked to an ESP8266. The Arduino spams serial out to the ESP8266 in its usual way. The ESP8266 then pipes all that out to a simple JavaScript webpage. Connect to the ESP8266’s IP with any device in your house, and get a live stream of all the serial data. Neat.

As simple as this technique is, we can see ourselves making a neat little box with TX, RX, GND, and VCC screw terminals to free us from the nightmare of tethering on concrete floors just for a simple test. Video after the break.


Filed under: Arduino Hacks, wireless hacks
Hack a Day 08 Mar 03:00

Intel Edison Arduino Expansion ---> dymanixel motors

I was wondering what the best method to control DYNAMIXEL AX-18A motors from an Intel Edison with arduino expansion board would be, I have teh Arbotix-M, the UartSBee, the Edison with Arduino Expansion Board, and the Arduino Uno. I really want to make it so that I can use the Intel Edison w/ expansion board, and send that to the Arbotix-M. Can you help me?

 

Many errors in my C code, communication with raspberry pi and arduino

#include <stdio.h>

#include <string.h>

#include <errno.h>

#include <wiringPi.h>

#include <wiringSerial.h>

 

 

#define TRIGsonar1 = 0;

#define TRIGsonar2 = 2;

#define TRIGsonar3 = 3;

#define TRIGsonar4 = 12;

#define TRIGsonar5 = 13;

#define TRIGsonar6 = 14;

#define TRIGsonar7 = 17;

#define TRIGsonar8 = 19;

 

#define ECHOsonar1 = 1;

#define ECHOsonar2 = 4;

#define ECHOsonar3 = 5;

#define ECHOsonar4 = 6;

read more

Serial Data from the Web to an Arduino

In the old days, a serial port often connected to an acoustic coupler that gripped a phone handset and allowed a remote connection to a far away serial port (via another phone and acoustic coupler) at a blistering 300 baud or less. The acoustic coupler would do the job of converting serial data to audio and reconstituting it after its trip through the phone lines. Modems advanced, but have mostly given way to DSL, Cable, Fiber, and other high speed networking options.

In a decidedly retro move, [James Halliday] and [jerky] put a modern spin on that old idea. They used the webaudio API to send serial data to a remote Arduino. The hack uses a FET, a capacitor, and a few resistors. They didn’t quite build a real modem with the audio. Instead, they basically spoof the audio port into sending serial data and recover it with the external circuitry. They also only implement serial sending (so the Arduino receives) so far, although they mention the next step would be to build the other side of the connection.

They say the data transmission is finicky, but it works (see the video below). We imagine using proper modem tones and decoders might work better, but would be a lot more effort. We’ve covered a 1200 baud modem before. We’ve also covered a bit of the theory behind them.


Filed under: Arduino Hacks, Network Hacks

Send HEX values to Arduino

FIVE MINUTE TUTORIAL

Project Description: Sending Hex values to an Arduino UNO


This simple tutorial will show you how to send Hexadecimal values from a computer to an Arduino Uno. The "Processing" programming language will be used to send the HEX values from the computer when a mouse button is pressed. The Arduino will use these values to adjust the brightness of an LED.



 

Learning Objectives


  • To Send Hexadecimal (Hex) values from a computer to the Arduino
  • Trigger an action based on the press of a mouse button
  • Learn to create a simple Computer to Arduino interface
  • Use Arduino's PWM capabilities to adjust brightness of an LED
  • Learn to use Arduino's analogWrite() function
  • Create a simple LED circuit


 

Parts Required:


Fritzing Sketch


The diagram below will show you how to connect an LED to Digital Pin 10 on the Arduino.
Don't forget the 330 ohm resistor !
 


 
 

Arduino Sketch


The latest version of Arduino IDE can be downloaded here.
 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
     Arduino IDE: 1.6.4
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Arduino Sketch used to adjust the brightness of an LED based on the values received
                  on the serial port. The LED needs to be connected to a PWM pin. In this sketch
                  Pin 10 is used, however you could use Pin 3, 5, 6, 9, or 11 - if you are using an Arduino Uno.
===================================================================================================================================================== */

byte byteRead; //Variable used to store the byte received on the Serial Port
int ledPin = 10; //LED is connected to Arduino Pin 10. This pin must be PWM capable.

void setup() {
 Serial.begin(9600); //Initialise Serial communication with the computer
 pinMode(ledPin, OUTPUT); //Set Pin 10 as an Output pin
 byteRead = 0;                   //Initialise the byteRead variable to zero.
}

void loop() {
  if(Serial.available()) {
    byteRead = Serial.read(); //Update the byteRead variable with the Hex value received on the Serial COM port.
  }
  
  analogWrite(ledPin, byteRead); //Use PWM to adjust the brightness of the LED. Brightness is determined by the "byteRead" variable.
}


 


 
 

Processing Sketch


The latest version of the Processing IDE can be downloaded here.
 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
  Processing IDE: 2.2.1
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Processing Sketch used to send HEX values from computer to Arduino when the mouse is pressed.
                  The alternating values 0xFF and 0x00 are sent to the Arduino Uno to turn an LED on and off.
                  You can send any HEX value from 0x00 to 0xFF. This sketch also shows how to convert Hex strings
                  to Hex numbers.
===================================================================================================================================================== */

import processing.serial.*; //This import statement is required for Serial communication

Serial comPort;                       //comPort is used to write Hex values to the Arduino
boolean toggle = false; //toggle variable is used to control which hex variable to send
String zeroHex = "00"; //This "00" string will be converted to 0x00 and sent to Arduino to turn LED off.
String FFHex = "FF"; //This "FF" string will be converted to 0xFF and sent to Arduino to turn LED on.

void setup(){
    comPort = new Serial(this, Serial.list()[0], 9600); //initialise the COM port for serial communication at a baud rate of 9600.
    delay(2000);                      //this delay allows the com port to initialise properly before initiating any communication.
    background(0); //Start with a black background.
    
}


void draw(){ //the draw() function is necessary for the sketch to compile
    //do nothing here //even though it does nothing.
}


void mousePressed(){ //This function is called when the mouse is pressed within the Processing window.
  toggle = ! toggle;                   //The toggle variable will change back and forth between "true" and "false"
  if(toggle){ //If the toggle variable is TRUE, then send 0xFF to the Arduino
     comPort.write(unhex(FFHex)); //The unhex() function converts the "FF" string to 0xFF
     background(0,0,255); //Change the background colour to blue as a visual indication of a button press.
  } else {
    comPort.write(unhex(zeroHex)); //If the toggle variable is FALSE, then send 0x00 to the Arduino
    background(0); //Change the background colour to black as a visual indication of a button press.
  }
}


 

The Video


 

The tutorial above is a quick demonstration of how to convert Hex strings on your computer and send them to an Arduino. The Arduino can use the values to change the brightness of an LED as shown in this tutorial, however you could use it to modify the speed of a motor, or to pass on commands to another module. Hopefully this short tutorial will help you with your project. Please let me know how it helped you in the comments below.

 
 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 
             


 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.

Send HEX values to Arduino

FIVE MINUTE TUTORIAL

Project Description: Sending Hex values to an Arduino UNO


This simple tutorial will show you how to send Hexadecimal values from a computer to an Arduino Uno. The "Processing" programming language will be used to send the HEX values from the computer when a mouse button is pressed. The Arduino will use these values to adjust the brightness of an LED.



 

Learning Objectives


  • To Send Hexadecimal (Hex) values from a computer to the Arduino
  • Trigger an action based on the press of a mouse button
  • Learn to create a simple Computer to Arduino interface
  • Use Arduino's PWM capabilities to adjust brightness of an LED
  • Learn to use Arduino's analogWrite() function
  • Create a simple LED circuit


 

Parts Required:


Fritzing Sketch


The diagram below will show you how to connect an LED to Digital Pin 10 on the Arduino.
Don't forget the 330 ohm resistor !
 


 
 

Arduino Sketch


The latest version of Arduino IDE can be downloaded here.
 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
     Arduino IDE: 1.6.4
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Arduino Sketch used to adjust the brightness of an LED based on the values received
                  on the serial port. The LED needs to be connected to a PWM pin. In this sketch
                  Pin 10 is used, however you could use Pin 3, 5, 6, 9, or 11 - if you are using an Arduino Uno.
===================================================================================================================================================== */

byte byteRead; //Variable used to store the byte received on the Serial Port
int ledPin = 10; //LED is connected to Arduino Pin 10. This pin must be PWM capable.

void setup() {
 Serial.begin(9600); //Initialise Serial communication with the computer
 pinMode(ledPin, OUTPUT); //Set Pin 10 as an Output pin
 byteRead = 0;                   //Initialise the byteRead variable to zero.
}

void loop() {
  if(Serial.available()) {
    byteRead = Serial.read(); //Update the byteRead variable with the Hex value received on the Serial COM port.
  }
  
  analogWrite(ledPin, byteRead); //Use PWM to adjust the brightness of the LED. Brightness is determined by the "byteRead" variable.
}


 


 
 

Processing Sketch


The latest version of the Processing IDE can be downloaded here.
 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
  Processing IDE: 2.2.1
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Processing Sketch used to send HEX values from computer to Arduino when the mouse is pressed.
                  The alternating values 0xFF and 0x00 are sent to the Arduino Uno to turn an LED on and off.
                  You can send any HEX value from 0x00 to 0xFF. This sketch also shows how to convert Hex strings
                  to Hex numbers.
===================================================================================================================================================== */

import processing.serial.*; //This import statement is required for Serial communication

Serial comPort;                       //comPort is used to write Hex values to the Arduino
boolean toggle = false; //toggle variable is used to control which hex variable to send
String zeroHex = "00"; //This "00" string will be converted to 0x00 and sent to Arduino to turn LED off.
String FFHex = "FF"; //This "FF" string will be converted to 0xFF and sent to Arduino to turn LED on.

void setup(){
    comPort = new Serial(this, Serial.list()[0], 9600); //initialise the COM port for serial communication at a baud rate of 9600.
    delay(2000);                      //this delay allows the com port to initialise properly before initiating any communication.
    background(0); //Start with a black background.
    
}


void draw(){ //the draw() function is necessary for the sketch to compile
    //do nothing here //even though it does nothing.
}


void mousePressed(){ //This function is called when the mouse is pressed within the Processing window.
  toggle = ! toggle;                   //The toggle variable will change back and forth between "true" and "false"
  if(toggle){ //If the toggle variable is TRUE, then send 0xFF to the Arduino
     comPort.write(unhex(FFHex)); //The unhex() function converts the "FF" string to 0xFF
     background(0,0,255); //Change the background colour to blue as a visual indication of a button press.
  } else {
    comPort.write(unhex(zeroHex)); //If the toggle variable is FALSE, then send 0x00 to the Arduino
    background(0); //Change the background colour to black as a visual indication of a button press.
  }
}


 

The Video


 

The tutorial above is a quick demonstration of how to convert Hex strings on your computer and send them to an Arduino. The Arduino can use the values to change the brightness of an LED as shown in this tutorial, however you could use it to modify the speed of a motor, or to pass on commands to another module. Hopefully this short tutorial will help you with your project. Please let me know how it helped you in the comments below.

 
 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 
             


 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.

CH376S USB Read/Write module

Have you ever wondered if there was a way to store and retrieve data from a USB stick with an Arduino UNO? Most people choose SD cards to store their project data, but you may be surprised there IS a way!
IC Station have a nice little module which allows you store and retrieve your Arduino (or other MCU) project data to a USB stick.
 
I am not too sure why USB storage is not widely used in Arduino projects? These modules are not expensive, they have been around for quite a while, and are relatively simple to use. You do not need any libraries to get them to work, however, I must say that documentation for this module is not that easy to find. This site and this document proved to be very useful in my endevour to get this module working, and I hope my tutorial below will help you get started and bridge some of the information gaps.
 
The "CH376S USB read/write module" has a CH376S chip onboard which does most of the hard work for you. All you have to do is send the module some commands from the Arduino and the CH376S chip will do the rest. You can communicate with the module in three different ways:

  • Parallel communication
  • SPI communication
  • and Serial (UART) communication.

This project will show you the connections and code for the Serial (UART) communication method only.


 

Parts Required:

Remove the Jumper

When the CH376S USB module arrives in it's package, it will have a jumper between the TXD pin and GND. You will need to remove this jumper to make the necessary connections between the Arduino UNO and the CH376S USB module.


 

Fritzing Sketch

Please note, that the Arduino Sketch makes use of the Arduino UNO's onboard LED on digital pin 13. The Fritzing sketch below shows an LED + 300 ohm resistor on a breadboard. This is optional. The LED is not a necessary component of CH376S module communication.

Also be aware that the CH376S USB module has an onboard LED just above the TXD and GND pins near the USB port. This LED will only turn on providing the CH376S module is in USB mode AND a USB device has been inserted into the USB port. Both conditions must be met before the module's onboard LED will illuminate. You will not see the LED turn on just by powering the board.
 
The wire diagram below is the correct setup for Serial communication between an Arduino UNO and the CH376S module. If you wish to use SPI or Parallel communication, you will need to refer to the datasheet.


 
 

Arduino Sketch


 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505

/* ===============================================================
      Project: CH376S USB Read/Write Module testing ground
       Author: Scott C
      Created: 1st May 2015
  Arduino IDE: 1.6.2
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: This project will allow you to perform many of the functions available on the CH376S module.
               Checking connection to the module, putting the module into USB mode, resetting the module, 
               reading, writing, appending text to files on the USB stick. This is very useful alternative to
               SD card modules, plus it doesn't need any libraries.
================================================================== */

#include <SoftwareSerial.h>

byte computerByte; //used to store data coming from the computer
byte USB_Byte; //used to store data coming from the USB stick
int LED = 13; //the LED is connected to digital pin 13
int timeOut = 2000; //TimeOut is 2 seconds. This is the amount of time you wish to wait for a response from the CH376S module.
String wrData = "What is the meaning of life ?"; //We will write this data to a newly created file.
String wrData2 = "42"; //We will append this data to an already existing file.

SoftwareSerial USB(10, 11); // Digital pin 10 on Arduino (RX) connects to TXD on the CH376S module
                                                      // Digital pin 11 on Arduino (TX) connects to RXD on the CH376S module
                                                      // GND on Arduino to GND on CH376S module
                                                      // 5V on Arduino to 5V on CH376S module
//==============================================================================================================================================
void setup() {
  Serial.begin(9600); // Setup serial communication with the computer (using a baud rate of 9600 on serial monitor)
  USB.begin(9600); // Setup serial communication with the CH376S module (using the default baud rate of 9600)
  pinMode(LED,OUTPUT); // Define digital pin 13 as an OUTPUT pin - so that we can use it with an LED
  digitalWrite(LED,LOW); // Turn off the LED
}

//================================================================================================================================================
void loop() {
  if(Serial.available()){
    computerByte = Serial.read(); //read any incoming bytes from the Serial monitor, and store this byte in the variable called computerByte
    if(computerByte==49){ //1 //If you send the number 1 from the serial monitor, the arduino will read it as digital number 49. Google "ascii table" for more info.
      printCommandHeader("COMMAND1: CHECK CONNECTION");
      checkConnection(0x01);                           // Check for successful connection and communication with the CH376S module.
    } 
    if(computerByte==50){ //2
     printCommandHeader("COMMAND2: set_USB_Mode");
      set_USB_Mode(0x06);                              // Code used to enable read/write communication and monitoring of the USB stick
    }
    if(computerByte==51){ //3
      printCommandHeader("COMMAND3: resetALL");
      resetALL();                                      // Reset the USB device
    }
    if(computerByte==52){ //4
      printCommandHeader("COMMAND4: Create and Write to File : TEST4.TXT");
      writeFile("TEST4.TXT", wrData); // Create a file called TEST4.TXT and then Write the contents of wrData to this file
    }
    if(computerByte==53){ //5
      printCommandHeader("COMMAND5: Read File: TEST4.TXT");
      readFile("TEST4.TXT"); // Read the contents of this file on the USB disk, and display contents in the Serial Monitor
    }
    if(computerByte==54){ //6
      printCommandHeader("COMMAND6: Append data to file: TEST4.TXT");
      appendFile("TEST4.TXT", wrData2); // Append data to the end of the file.
    }
    if(computerByte==55){ //7
      printCommandHeader("COMMAND7: Delete File: TEST4.TXT");
      fileDelete("TEST4.TXT"); // Delete the file named TEST4.TXT
    }
    if(computerByte==56){ //8
      printCommandHeader("COMMAND8: Read File: TEST2.TXT");
      readFile("TEST2.TXT"); // Read the contents of the TEST2.TXT file on the USB disk, and display contents in the Serial Monitor
    }
    if(computerByte==57){ //9
      printCommandHeader("COMMAND9: Read File: TEST3.TXT");
      readFile("TEST3.TXT"); // Read the contents of the TEST3.TXT file on the USB disk, and display contents in the Serial Monitor
    }
  }
  
  if(USB.available()){ // This is here to capture any unexpected data transmitted by the CH376S module
    Serial.print("CH376S has just sent this code:");
    Serial.println(USB.read(), HEX);
  }
}

//END OF LOOP FUNCTION ========================================================================================================================================

//print Command header
void printCommandHeader(String header){
   Serial.println("======================");
   Serial.println("");
   Serial.println(header);
   Serial.println("----------------------");
}

//checkConnection==================================================================================
//This function is used to check for successful communication with the CH376S module. This is not dependant of the presence of a USB stick.
//Send any value between 0 to 255, and the CH376S module will return a number = 255 - value. 
void checkConnection(byte value){
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x06);
  USB.write(value);
  
  if(waitForResponse("checking connection")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==(255-value)){
       Serial.println(">Connection to CH376S was successful.");
       blinkLED();                               //blink the LED for 1 second if the connection was successful
    } else {
      Serial.print(">Connection to CH376S - FAILED.");
    }
  }
}

//set_USB_Mode=====================================================================================
//Make sure that the USB is inserted when using 0x06 as the value in this specific code sequence
void set_USB_Mode (byte value){
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x15);
  USB.write(value);
  
  delay(20);
  
  if(USB.available()){
    USB_Byte=USB.read();
    //Check to see if the command has been successfully transmitted and acknowledged.
    if(USB_Byte==0x51){ // If true - the CH376S has acknowledged the command.
        Serial.println("set_USB_Mode command acknowledged"); //The CH376S will now check and monitor the USB port
        USB_Byte = USB.read();
        
        //Check to see if the USB stick is connected or not.
        if(USB_Byte==0x15){ // If true - there is a USB stick connected
          Serial.println("USB is present");
          blinkLED();                                     // If the process was successful, then turn the LED on for 1 second
        } else {
          Serial.print("USB Not present. Error code:"); // If the USB is not connected - it should return an Error code = FFH
          Serial.print(USB_Byte, HEX);
          Serial.println("H");
        }
        
    } else {
        Serial.print("CH3765 error! Error code:");
        Serial.print(USB_Byte, HEX);
        Serial.println("H");
    }   
  }
  delay(20);
}

//resetALL=========================================================================================
//This will perform a hardware reset of the CH376S module - which usually takes about 35 msecs =====
void resetALL(){
    USB.write(0x57);
    USB.write(0xAB);
    USB.write(0x05);
    Serial.println("The CH376S module has been reset !");
    delay(200);
}

//readFile=====================================================================================
//This will send a series of commands to read data from a specific file (defined by fileName)
void readFile(String fileName){
  resetALL();                     //Reset the module
  set_USB_Mode(0x06);             //Set to USB Mode
  diskConnectionStatus();         //Check that communication with the USB device is possible
  USBdiskMount();                 //Prepare the USB for reading/writing - you need to mount the USB disk for proper read/write operations.
  setFileName(fileName);          //Set File name
  fileOpen();                     //Open the file for reading
  int fs = getFileSize(); //Get the size of the file
  fileRead();                     //***** Send the command to read the file ***
  fileClose(0x00);                //Close the file
}

//writeFile========================================================================================
//is used to create a new file and then write data to that file. "fileName" is a variable used to hold the name of the file (e.g TEST.TXT). "data" should not be greater than 255 bytes long. 
void writeFile(String fileName, String data){
  resetALL();                     //Reset the module
  set_USB_Mode(0x06);             //Set to USB Mode
  diskConnectionStatus();         //Check that communication with the USB device is possible
  USBdiskMount();                 //Prepare the USB for reading/writing - you need to mount the USB disk for proper read/write operations.
  setFileName(fileName);          //Set File name
  if(fileCreate()){ //Try to create a new file. If file creation is successful
    fileWrite(data);              //write data to the file.
  } else {
    Serial.println("File could not be created, or it already exists");
  }
  fileClose(0x01);
}

//appendFile()====================================================================================
//is used to write data to the end of the file, without erasing the contents of the file.
void appendFile(String fileName, String data){
    resetALL();                     //Reset the module
    set_USB_Mode(0x06);             //Set to USB Mode
    diskConnectionStatus();         //Check that communication with the USB device is possible
    USBdiskMount();                 //Prepare the USB for reading/writing - you need to mount the USB disk for proper read/write operations.
    setFileName(fileName);          //Set File name
    fileOpen();                     //Open the file
    filePointer(false); //filePointer(false) is to set the pointer at the end of the file. filePointer(true) will set the pointer to the beginning.
    fileWrite(data);                //Write data to the end of the file
    fileClose(0x01);                //Close the file using 0x01 - which means to update the size of the file on close.
}
  
//setFileName======================================================================================
//This sets the name of the file to work with
void setFileName(String fileName){
  Serial.print("Setting filename to:");
  Serial.println(fileName);
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x2F);
  USB.write(0x2F); // Every filename must have this byte to indicate the start of the file name.
  USB.print(fileName); // "fileName" is a variable that holds the name of the file. eg. TEST.TXT
  USB.write((byte)0x00); // you need to cast as a byte - otherwise it will not compile. The null byte indicates the end of the file name.
  delay(20);
}

//diskConnectionStatus================================================================================
//Check the disk connection status
void diskConnectionStatus(){
  Serial.println("Checking USB disk connection status");
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x30);

  if(waitForResponse("Connecting to USB disk")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==0x14){ //CH376S will send 0x14 if this command was successful
       Serial.println(">Connection to USB OK");
    } else {
      Serial.print(">Connection to USB - FAILED.");
    }
  }
}

//USBdiskMount========================================================================================
//initialise the USB disk and check that it is ready - this process is required if you want to find the manufacturing information of the USB disk
void USBdiskMount(){
  Serial.println("Mounting USB disk");
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x31);

  if(waitForResponse("mounting USB disk")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==0x14){ //CH376S will send 0x14 if this command was successful
       Serial.println(">USB Mounted - OK");
    } else {
      Serial.print(">Failed to Mount USB disk.");
    }
  }
}

//fileOpen========================================================================================
//opens the file for reading or writing
void fileOpen(){
  Serial.println("Opening file.");
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x32);
  if(waitForResponse("file Open")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==0x14){ //CH376S will send 0x14 if this command was successful
       Serial.println(">File opened successfully.");
    } else {
      Serial.print(">Failed to open file.");
    }
  }
}

//setByteRead=====================================================================================
//This function is required if you want to read data from the file. 
boolean setByteRead(byte numBytes){
  boolean bytesToRead=false;
  int timeCounter = 0;
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x3A);
  USB.write((byte)numBytes); //tells the CH376S how many bytes to read at a time
  USB.write((byte)0x00);
  if(waitForResponse("setByteRead")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==0x1D){ //read the CH376S message. If equal to 0x1D, data is present, so return true. Will return 0x14 if no data is present.
      bytesToRead=true;
    }
  }
  return(bytesToRead);


//getFileSize()===================================================================================
//writes the file size to the serial Monitor.
int getFileSize(){
  int fileSize=0;
  Serial.println("Getting File Size");
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x0C);
  USB.write(0x68);
  delay(100);
  Serial.print("FileSize =");
  if(USB.available()){
    fileSize = fileSize + USB.read();
  } 
  if(USB.available()){
    fileSize = fileSize + (USB.read()*255);
  } 
  if(USB.available()){
    fileSize = fileSize + (USB.read()*255*255);
  } 
  if(USB.available()){
    fileSize = fileSize + (USB.read()*255*255*255);
  }     
  Serial.println(fileSize);
  delay(10);
  return(fileSize);
}


//fileRead========================================================================================
//read the contents of the file
void fileRead(){
  Serial.println("Reading file:");
  byte firstByte = 0x00; //Variable to hold the firstByte from every transmission. Can be used as a checkSum if required.
  byte numBytes = 0x40; //The maximum value is 0x40 = 64 bytes
 
  while(setByteRead(numBytes)){ //This tells the CH376S module how many bytes to read on the next reading step. In this example, we will read 0x10 bytes at a time. Returns true if there are bytes to read, false if there are no more bytes to read.
    USB.write(0x57);
    USB.write(0xAB);
    USB.write(0x27); //Command to read ALL of the bytes (allocated by setByteRead(x))
    if(waitForResponse("reading data")){ //Wait for the CH376S module to return data. TimeOut will return false. If data is being transmitted, it will return true.
        firstByte=USB.read(); //Read the first byte
        while(USB.available()){
          Serial.write(USB.read()); //Send the data from the USB disk to the Serial monitor
          delay(1); //This delay is necessary for successful Serial transmission
        }
    }
    if<!continueRead()){><span>//prepares the module for further reading. If false, stop reading.</span><br />      <span>break</span>; <span>//You need the continueRead() method if the data to be read from the USB device is greater than numBytes.</span><br />    }<br />  }<br />  <span><b>Serial</b></span>.<span>println</span>();<br />  <span><b>Serial</b></span>.<span>println</span>(<span>"NO MORE DATA"</span>);<br />}<br /><br /><span>//fileWrite=======================================================================================</span><br /><span>//are the commands used to write to the file</span><br /><span>void</span> fileWrite(<span>String</span> data){<br />  <span><b>Serial</b></span>.<span>println</span>(<span>"Writing to file:"</span>);<br />  <span>byte</span> dataLength = (<span>byte</span>) data.<span>length</span>(); <span>// This variable holds the length of the data to be written (in bytes)</span><br />  <span><b>Serial</b></span>.<span>println</span>(data);<br />  <span><b>Serial</b></span>.<span>print</span>(<span>"Data Length:"</span>);<br />  <span><b>Serial</b></span>.<span>println</span>(dataLength);<br />  <span>delay</span>(100);<br />  <span>// This set of commands tells the CH376S module how many bytes to expect from the Arduino. (defined by the "dataLength" variable)</span><br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x3C);<br />  USB.<span>write</span>((<span>byte</span>) dataLength);<br />  USB.<span>write</span>((<span>byte</span>) 0x00);<br />  <span>if</span>(waitForResponse(<span>"setting data Length"</span>)){ <span>// Wait for an acknowledgement from the CH376S module before trying to send data to it</span><br />    <span>if</span>(getResponseFromUSB()==0x1E){ <span>// 0x1E indicates that the USB device is in write mode.</span><br />      USB.<span>write</span>(0x57);<br />      USB.<span>write</span>(0xAB);<br />      USB.<span>write</span>(0x2D);<br />      USB.<span>print</span>(data); <span>// write the data to the file</span><br />  <br />      <span>if</span>(waitForResponse(<span>"writing data to file"</span>)){ <span>// wait for an acknowledgement from the CH376S module</span><br />      }<br />      <span><b>Serial</b></span>.<span>print</span>(<span>"Write code (normally FF and 14): "</span>);<br />      <span><b>Serial</b></span>.<span>print</span>(USB.<span>read</span>(),<span>HEX</span>); <span>// code is normally 0xFF</span><br />      <span><b>Serial</b></span>.<span>print</span>(<span>","</span>);<br />      USB.<span>write</span>(0x57);<br />      USB.<span>write</span>(0xAB);<br />      USB.<span>write</span>(0x3D); <span>// This is used to update the file size. Not sure if this is necessary for successful writing.</span><br />      <span>if</span>(waitForResponse(<span>"updating file size"</span>)){ <span>// wait for an acknowledgement from the CH376S module</span><br />      }<br />      <span><b>Serial</b></span>.<span>println</span>(USB.<span>read</span>(),<span>HEX</span>); <span>//code is normally 0x14</span><br />    }<br />  }<br />}<br /><br /><span>//continueRead()==================================================================================</span><br /><span>//continue to read the file : I could not get this function to work as intended.</span><br /><span>boolean</span> continueRead(){<br />  <span>boolean</span> readAgain = <span>false</span>;<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x3B);<br />  <span>if</span>(waitForResponse(<span>"continueRead"</span>)){ <span>//wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.</span><br />     <span>if</span>(getResponseFromUSB()==0x14){ <span>//CH376S will send 0x14 if this command was successful</span><br />       readAgain=<span>true</span>;<br />     }<br />  }<br />  <span>return</span>(readAgain);<br />} <br /><br /><span>//fileCreate()========================================================================================</span><br /><span>//the command sequence to create a file</span><br /><span>boolean</span> fileCreate(){<br />  <span>boolean</span> createdFile = <span>false</span>;<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x34);<br />  <span>if</span>(waitForResponse(<span>"creating file"</span>)){ <span>//wait for a response from the CH376S. If file has been created successfully, it will return true.</span><br />     <span>if</span>(getResponseFromUSB()==0x14){ <span>//CH376S will send 0x14 if this command was successful</span><br />       createdFile=<span>true</span>;<br />     }<br />  }<br />  <span>return</span>(createdFile);<br />}<br /><br /><br /><span>//fileDelete()========================================================================================</span><br /><span>//the command sequence to delete a file</span><br /><span>void</span> fileDelete(<span>String</span> fileName){<br />  setFileName(fileName);<br />  <span>delay</span>(20);<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x35);<br />  <span>if</span>(waitForResponse(<span>"deleting file"</span>)){ <span>//wait for a response from the CH376S. If file has been created successfully, it will return true.</span><br />     <span>if</span>(getResponseFromUSB()==0x14){ <span>//CH376S will send 0x14 if this command was successful</span><br />       <span><b>Serial</b></span>.<span>println</span>(<span>"Successfully deleted file"</span>);<br />     }<br />  }<br />}<br />  <br /><br /><span>//filePointer========================================================================================</span><br /><span>//is used to set the file pointer position. true for beginning of file, false for the end of the file.</span><br /><span>void</span> filePointer(<span>boolean</span> fileBeginning){<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x39);<br />  <span>if</span>(fileBeginning){<br />    USB.<span>write</span>((<span>byte</span>)0x00); <span>//beginning of file</span><br />    USB.<span>write</span>((<span>byte</span>)0x00);<br />    USB.<span>write</span>((<span>byte</span>)0x00);<br />    USB.<span>write</span>((<span>byte</span>)0x00);<br />  } <span>else</span> {<br />    USB.<span>write</span>((<span>byte</span>)0xFF); <span>//end of file</span><br />    USB.<span>write</span>((<span>byte</span>)0xFF);<br />    USB.<span>write</span>((<span>byte</span>)0xFF);<br />    USB.<span>write</span>((<span>byte</span>)0xFF);<br />  }<br />  <span>if</span>(waitForResponse(<span>"setting file pointer"</span>)){ <span>//wait for a response from the CH376S. </span><br />     <span>if</span>(getResponseFromUSB()==0x14){ <span>//CH376S will send 0x14 if this command was successful</span><br />       <span><b>Serial</b></span>.<span>println</span>(<span>"Pointer successfully applied"</span>);<br />     }<br />  }<br />}<br /><br /><br /><span>//fileClose=======================================================================================</span><br /><span>//closes the file</span><br /><span>void</span> fileClose(<span>byte</span> closeCmd){<br />  <span><b>Serial</b></span>.<span>println</span>(<span>"Closing file:"</span>);<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x36);<br />  USB.<span>write</span>((<span>byte</span>)closeCmd); <span>// closeCmd = 0x00 = close without updating file Size, 0x01 = close and update file Size</span><br /><br />  <span>if</span>(waitForResponse(<span>"closing file"</span>)){ <span>// wait for a response from the CH376S. </span><br />     <span>byte</span> resp = getResponseFromUSB();<br />     <span>if</span>(resp==0x14){ <span>// CH376S will send 0x14 if this command was successful</span><br />       <span><b>Serial</b></span>.<span>println</span>(<span>">File closed successfully."</span>);<br />     } <span>else</span> {<br />       <span><b>Serial</b></span>.<span>print</span>(<span>">Failed to close file. Error code:"</span>);<br />       <span><b>Serial</b></span>.<span>println</span>(resp, <span>HEX</span>);<br />     }  <br />  }<br />}<br /><br /><span>//waitForResponse===================================================================================</span><br /><span>//is used to wait for a response from USB. Returns true when bytes become available, false if it times out.</span><br /><span>boolean</span> waitForResponse(<span>String</span> errorMsg){<br />  <span>boolean</span> bytesAvailable = <span>true</span>;<br />  <span>int</span> counter=0;<br />  <span>while</span><!USB><span>available</span>()){ <span>//wait for CH376S to verify command</span><br />    <span>delay</span>(1);<br />    counter++;<br />    <span>if</span>(counter>timeOut){<br />      <span><b>Serial</b></span>.<span>print</span>(<span>"TimeOut waiting for response: Error while: "</span>);<br />      <span><b>Serial</b></span>.<span>println</span>(errorMsg);<br />      bytesAvailable = <span>false</span>;<br />      <span>break</span>;<br />    }<br />  }<br />  <span>delay</span>(1);<br />  <span>return</span>(bytesAvailable);<br />}<br /><br /><span>//getResponseFromUSB================================================================================</span><br /><span>//is used to get any error codes or messages from the CH376S module (in response to certain commands)</span><br /><span>byte</span> getResponseFromUSB(){<br />  <span>byte</span> response = <span>byte</span>(0x00);<br />  <span>if</span> (USB.<span>available</span>()){<br />    response = USB.<span>read</span>();<br />  }<br />  <span>return</span>(response);<br />}<br /><br /><br /><br /><span>//blinkLED==========================================================================================</span><br /><span>//Turn an LED on for 1 second</span><br /><span>void</span> blinkLED(){<br />  <span>digitalWrite</span>(LED, <span>HIGH</span>);<br />  <span>delay</span>(1000);<br />  <span>digitalWrite</span>(LED,<span>LOW</span>);<br />}<br /><br /></pre> </td> </tr> </table></div></p> <br /> <p> If you copy and paste this code directly into the Arduino IDE; you may get a warning like this when you compile the code:<br />   <br />    "Low memory available, stability problems may occur". <br />  <br /> I managed to run the sketch without any issues, however, I did experience problems with some of the methods when I had made further memory hungry modifications. If you do encounter problems, I would recommend that you eliminate any methods which you do not plan to use, and perhaps reduce the number of Serial.print statements throughout the code. However, please note that some of the methods will not work unless the module is in the correct state, so be careful which methods you delete. For example, I found that I could get some simple functionality without the "USBdiskMount()" method. However, I could not read/write data beyond a certain length without this method.<br />   <br /> Also please note, that some of the methods called within the reading and writing sequence do not need to be called every time. They can be called once in setup, while other methods within the sequence will need to be called every time. I grouped them all together for simplicity. </p> <!--separator --><img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <p><h4>Serial Commands</h4> Have a look at the following presentation for a summary of the Serial commands used in this tutorial: <br />   <br /> <div> </div> </p> </div><p> <div> <!-- Concluding Comments --> </div> <br />  <br />  <div> <p> <!--separator --> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p> </div> </p><p> <div> If you like this page, please do me a favour and show your appreciation : <br /> <br />  <br /> Visit my <a href="https://plus.google.com/u/0/b/107402020974762902161/107402020974762902161/posts">ArduinoBasics Google + page</a>.<br /> Follow me on Twitter by looking for <a href="https://twitter.com/ArduinoBasics">ScottC @ArduinoBasics</a>.<br /> I can also be found on <a href="https://www.pinterest.com/ArduinoBasics/">Pinterest</a> and <a href="https://instagram.com/arduinobasics">Instagram</a>. <br /> Have a look at my videos on my <a href="https://www.youtube.com/user/ScottCMe/videos">YouTube channel</a>.<br /> </div> </p> <br /> <div> <p> <!--separator --> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p> </div> <p> However, if you do not have a google profile... <br />Feel free to share this page with your friends in any way you see fit. </p>

CH376S USB Read/Write module

Have you ever wondered if there was a way to store and retrieve data from a USB stick with an Arduino UNO? Most people choose SD cards to store their project data, but you may be surprised there IS a way!
IC Station have a nice little module which allows you store and retrieve your Arduino (or other MCU) project data to a USB stick.
 
I am not too sure why USB storage is not widely used in Arduino projects? These modules are not expensive, they have been around for quite a while, and are relatively simple to use. You do not need any libraries to get them to work, however, I must say that documentation for this module is not that easy to find. This site and this document proved to be very useful in my endevour to get this module working, and I hope my tutorial below will help you get started and bridge some of the information gaps.
 
The "CH376S USB read/write module" has a CH376S chip onboard which does most of the hard work for you. All you have to do is send the module some commands from the Arduino and the CH376S chip will do the rest. You can communicate with the module in three different ways:

  • Parallel communication
  • SPI communication
  • and Serial (UART) communication.

This project will show you the connections and code for the Serial (UART) communication method only.


 

Parts Required:

Remove the Jumper

When the CH376S USB module arrives in it's package, it will have a jumper between the TXD pin and GND. You will need to remove this jumper to make the necessary connections between the Arduino UNO and the CH376S USB module.


 

Fritzing Sketch

Please note, that the Arduino Sketch makes use of the Arduino UNO's onboard LED on digital pin 13. The Fritzing sketch below shows an LED + 300 ohm resistor on a breadboard. This is optional. The LED is not a necessary component of CH376S module communication.

Also be aware that the CH376S USB module has an onboard LED just above the TXD and GND pins near the USB port. This LED will only turn on providing the CH376S module is in USB mode AND a USB device has been inserted into the USB port. Both conditions must be met before the module's onboard LED will illuminate. You will not see the LED turn on just by powering the board.
 
The wire diagram below is the correct setup for Serial communication between an Arduino UNO and the CH376S module. If you wish to use SPI or Parallel communication, you will need to refer to the datasheet.


 
 

Arduino Sketch


 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505

/* ===============================================================
      Project: CH376S USB Read/Write Module testing ground
       Author: Scott C
      Created: 1st May 2015
  Arduino IDE: 1.6.2
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: This project will allow you to perform many of the functions available on the CH376S module.
               Checking connection to the module, putting the module into USB mode, resetting the module, 
               reading, writing, appending text to files on the USB stick. This is very useful alternative to
               SD card modules, plus it doesn't need any libraries.
================================================================== */

#include <SoftwareSerial.h>

byte computerByte; //used to store data coming from the computer
byte USB_Byte; //used to store data coming from the USB stick
int LED = 13; //the LED is connected to digital pin 13
int timeOut = 2000; //TimeOut is 2 seconds. This is the amount of time you wish to wait for a response from the CH376S module.
String wrData = "What is the meaning of life ?"; //We will write this data to a newly created file.
String wrData2 = "42"; //We will append this data to an already existing file.

SoftwareSerial USB(10, 11); // Digital pin 10 on Arduino (RX) connects to TXD on the CH376S module
                                                      // Digital pin 11 on Arduino (TX) connects to RXD on the CH376S module
                                                      // GND on Arduino to GND on CH376S module
                                                      // 5V on Arduino to 5V on CH376S module
//==============================================================================================================================================
void setup() {
  Serial.begin(9600); // Setup serial communication with the computer (using a baud rate of 9600 on serial monitor)
  USB.begin(9600); // Setup serial communication with the CH376S module (using the default baud rate of 9600)
  pinMode(LED,OUTPUT); // Define digital pin 13 as an OUTPUT pin - so that we can use it with an LED
  digitalWrite(LED,LOW); // Turn off the LED
}

//================================================================================================================================================
void loop() {
  if(Serial.available()){
    computerByte = Serial.read(); //read any incoming bytes from the Serial monitor, and store this byte in the variable called computerByte
    if(computerByte==49){ //1 //If you send the number 1 from the serial monitor, the arduino will read it as digital number 49. Google "ascii table" for more info.
      printCommandHeader("COMMAND1: CHECK CONNECTION");
      checkConnection(0x01);                           // Check for successful connection and communication with the CH376S module.
    } 
    if(computerByte==50){ //2
     printCommandHeader("COMMAND2: set_USB_Mode");
      set_USB_Mode(0x06);                              // Code used to enable read/write communication and monitoring of the USB stick
    }
    if(computerByte==51){ //3
      printCommandHeader("COMMAND3: resetALL");
      resetALL();                                      // Reset the USB device
    }
    if(computerByte==52){ //4
      printCommandHeader("COMMAND4: Create and Write to File : TEST4.TXT");
      writeFile("TEST4.TXT", wrData); // Create a file called TEST4.TXT and then Write the contents of wrData to this file
    }
    if(computerByte==53){ //5
      printCommandHeader("COMMAND5: Read File: TEST4.TXT");
      readFile("TEST4.TXT"); // Read the contents of this file on the USB disk, and display contents in the Serial Monitor
    }
    if(computerByte==54){ //6
      printCommandHeader("COMMAND6: Append data to file: TEST4.TXT");
      appendFile("TEST4.TXT", wrData2); // Append data to the end of the file.
    }
    if(computerByte==55){ //7
      printCommandHeader("COMMAND7: Delete File: TEST4.TXT");
      fileDelete("TEST4.TXT"); // Delete the file named TEST4.TXT
    }
    if(computerByte==56){ //8
      printCommandHeader("COMMAND8: Read File: TEST2.TXT");
      readFile("TEST2.TXT"); // Read the contents of the TEST2.TXT file on the USB disk, and display contents in the Serial Monitor
    }
    if(computerByte==57){ //9
      printCommandHeader("COMMAND9: Read File: TEST3.TXT");
      readFile("TEST3.TXT"); // Read the contents of the TEST3.TXT file on the USB disk, and display contents in the Serial Monitor
    }
  }
  
  if(USB.available()){ // This is here to capture any unexpected data transmitted by the CH376S module
    Serial.print("CH376S has just sent this code:");
    Serial.println(USB.read(), HEX);
  }
}

//END OF LOOP FUNCTION ========================================================================================================================================

//print Command header
void printCommandHeader(String header){
   Serial.println("======================");
   Serial.println("");
   Serial.println(header);
   Serial.println("----------------------");
}

//checkConnection==================================================================================
//This function is used to check for successful communication with the CH376S module. This is not dependant of the presence of a USB stick.
//Send any value between 0 to 255, and the CH376S module will return a number = 255 - value. 
void checkConnection(byte value){
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x06);
  USB.write(value);
  
  if(waitForResponse("checking connection")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==(255-value)){
       Serial.println(">Connection to CH376S was successful.");
       blinkLED();                               //blink the LED for 1 second if the connection was successful
    } else {
      Serial.print(">Connection to CH376S - FAILED.");
    }
  }
}

//set_USB_Mode=====================================================================================
//Make sure that the USB is inserted when using 0x06 as the value in this specific code sequence
void set_USB_Mode (byte value){
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x15);
  USB.write(value);
  
  delay(20);
  
  if(USB.available()){
    USB_Byte=USB.read();
    //Check to see if the command has been successfully transmitted and acknowledged.
    if(USB_Byte==0x51){ // If true - the CH376S has acknowledged the command.
        Serial.println("set_USB_Mode command acknowledged"); //The CH376S will now check and monitor the USB port
        USB_Byte = USB.read();
        
        //Check to see if the USB stick is connected or not.
        if(USB_Byte==0x15){ // If true - there is a USB stick connected
          Serial.println("USB is present");
          blinkLED();                                     // If the process was successful, then turn the LED on for 1 second
        } else {
          Serial.print("USB Not present. Error code:"); // If the USB is not connected - it should return an Error code = FFH
          Serial.print(USB_Byte, HEX);
          Serial.println("H");
        }
        
    } else {
        Serial.print("CH3765 error! Error code:");
        Serial.print(USB_Byte, HEX);
        Serial.println("H");
    }   
  }
  delay(20);
}

//resetALL=========================================================================================
//This will perform a hardware reset of the CH376S module - which usually takes about 35 msecs =====
void resetALL(){
    USB.write(0x57);
    USB.write(0xAB);
    USB.write(0x05);
    Serial.println("The CH376S module has been reset !");
    delay(200);
}

//readFile=====================================================================================
//This will send a series of commands to read data from a specific file (defined by fileName)
void readFile(String fileName){
  resetALL();                     //Reset the module
  set_USB_Mode(0x06);             //Set to USB Mode
  diskConnectionStatus();         //Check that communication with the USB device is possible
  USBdiskMount();                 //Prepare the USB for reading/writing - you need to mount the USB disk for proper read/write operations.
  setFileName(fileName);          //Set File name
  fileOpen();                     //Open the file for reading
  int fs = getFileSize(); //Get the size of the file
  fileRead();                     //***** Send the command to read the file ***
  fileClose(0x00);                //Close the file
}

//writeFile========================================================================================
//is used to create a new file and then write data to that file. "fileName" is a variable used to hold the name of the file (e.g TEST.TXT). "data" should not be greater than 255 bytes long. 
void writeFile(String fileName, String data){
  resetALL();                     //Reset the module
  set_USB_Mode(0x06);             //Set to USB Mode
  diskConnectionStatus();         //Check that communication with the USB device is possible
  USBdiskMount();                 //Prepare the USB for reading/writing - you need to mount the USB disk for proper read/write operations.
  setFileName(fileName);          //Set File name
  if(fileCreate()){ //Try to create a new file. If file creation is successful
    fileWrite(data);              //write data to the file.
  } else {
    Serial.println("File could not be created, or it already exists");
  }
  fileClose(0x01);
}

//appendFile()====================================================================================
//is used to write data to the end of the file, without erasing the contents of the file.
void appendFile(String fileName, String data){
    resetALL();                     //Reset the module
    set_USB_Mode(0x06);             //Set to USB Mode
    diskConnectionStatus();         //Check that communication with the USB device is possible
    USBdiskMount();                 //Prepare the USB for reading/writing - you need to mount the USB disk for proper read/write operations.
    setFileName(fileName);          //Set File name
    fileOpen();                     //Open the file
    filePointer(false); //filePointer(false) is to set the pointer at the end of the file. filePointer(true) will set the pointer to the beginning.
    fileWrite(data);                //Write data to the end of the file
    fileClose(0x01);                //Close the file using 0x01 - which means to update the size of the file on close.
}
  
//setFileName======================================================================================
//This sets the name of the file to work with
void setFileName(String fileName){
  Serial.print("Setting filename to:");
  Serial.println(fileName);
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x2F);
  USB.write(0x2F); // Every filename must have this byte to indicate the start of the file name.
  USB.print(fileName); // "fileName" is a variable that holds the name of the file. eg. TEST.TXT
  USB.write((byte)0x00); // you need to cast as a byte - otherwise it will not compile. The null byte indicates the end of the file name.
  delay(20);
}

//diskConnectionStatus================================================================================
//Check the disk connection status
void diskConnectionStatus(){
  Serial.println("Checking USB disk connection status");
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x30);

  if(waitForResponse("Connecting to USB disk")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==0x14){ //CH376S will send 0x14 if this command was successful
       Serial.println(">Connection to USB OK");
    } else {
      Serial.print(">Connection to USB - FAILED.");
    }
  }
}

//USBdiskMount========================================================================================
//initialise the USB disk and check that it is ready - this process is required if you want to find the manufacturing information of the USB disk
void USBdiskMount(){
  Serial.println("Mounting USB disk");
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x31);

  if(waitForResponse("mounting USB disk")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==0x14){ //CH376S will send 0x14 if this command was successful
       Serial.println(">USB Mounted - OK");
    } else {
      Serial.print(">Failed to Mount USB disk.");
    }
  }
}

//fileOpen========================================================================================
//opens the file for reading or writing
void fileOpen(){
  Serial.println("Opening file.");
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x32);
  if(waitForResponse("file Open")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==0x14){ //CH376S will send 0x14 if this command was successful
       Serial.println(">File opened successfully.");
    } else {
      Serial.print(">Failed to open file.");
    }
  }
}

//setByteRead=====================================================================================
//This function is required if you want to read data from the file. 
boolean setByteRead(byte numBytes){
  boolean bytesToRead=false;
  int timeCounter = 0;
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x3A);
  USB.write((byte)numBytes); //tells the CH376S how many bytes to read at a time
  USB.write((byte)0x00);
  if(waitForResponse("setByteRead")){ //wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.
    if(getResponseFromUSB()==0x1D){ //read the CH376S message. If equal to 0x1D, data is present, so return true. Will return 0x14 if no data is present.
      bytesToRead=true;
    }
  }
  return(bytesToRead);


//getFileSize()===================================================================================
//writes the file size to the serial Monitor.
int getFileSize(){
  int fileSize=0;
  Serial.println("Getting File Size");
  USB.write(0x57);
  USB.write(0xAB);
  USB.write(0x0C);
  USB.write(0x68);
  delay(100);
  Serial.print("FileSize =");
  if(USB.available()){
    fileSize = fileSize + USB.read();
  } 
  if(USB.available()){
    fileSize = fileSize + (USB.read()*255);
  } 
  if(USB.available()){
    fileSize = fileSize + (USB.read()*255*255);
  } 
  if(USB.available()){
    fileSize = fileSize + (USB.read()*255*255*255);
  }     
  Serial.println(fileSize);
  delay(10);
  return(fileSize);
}


//fileRead========================================================================================
//read the contents of the file
void fileRead(){
  Serial.println("Reading file:");
  byte firstByte = 0x00; //Variable to hold the firstByte from every transmission. Can be used as a checkSum if required.
  byte numBytes = 0x40; //The maximum value is 0x40 = 64 bytes
 
  while(setByteRead(numBytes)){ //This tells the CH376S module how many bytes to read on the next reading step. In this example, we will read 0x10 bytes at a time. Returns true if there are bytes to read, false if there are no more bytes to read.
    USB.write(0x57);
    USB.write(0xAB);
    USB.write(0x27); //Command to read ALL of the bytes (allocated by setByteRead(x))
    if(waitForResponse("reading data")){ //Wait for the CH376S module to return data. TimeOut will return false. If data is being transmitted, it will return true.
        firstByte=USB.read(); //Read the first byte
        while(USB.available()){
          Serial.write(USB.read()); //Send the data from the USB disk to the Serial monitor
          delay(1); //This delay is necessary for successful Serial transmission
        }
    }
    if<!continueRead()){><span>//prepares the module for further reading. If false, stop reading.</span><br />      <span>break</span>; <span>//You need the continueRead() method if the data to be read from the USB device is greater than numBytes.</span><br />    }<br />  }<br />  <span><b>Serial</b></span>.<span>println</span>();<br />  <span><b>Serial</b></span>.<span>println</span>(<span>"NO MORE DATA"</span>);<br />}<br /><br /><span>//fileWrite=======================================================================================</span><br /><span>//are the commands used to write to the file</span><br /><span>void</span> fileWrite(<span>String</span> data){<br />  <span><b>Serial</b></span>.<span>println</span>(<span>"Writing to file:"</span>);<br />  <span>byte</span> dataLength = (<span>byte</span>) data.<span>length</span>(); <span>// This variable holds the length of the data to be written (in bytes)</span><br />  <span><b>Serial</b></span>.<span>println</span>(data);<br />  <span><b>Serial</b></span>.<span>print</span>(<span>"Data Length:"</span>);<br />  <span><b>Serial</b></span>.<span>println</span>(dataLength);<br />  <span>delay</span>(100);<br />  <span>// This set of commands tells the CH376S module how many bytes to expect from the Arduino. (defined by the "dataLength" variable)</span><br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x3C);<br />  USB.<span>write</span>((<span>byte</span>) dataLength);<br />  USB.<span>write</span>((<span>byte</span>) 0x00);<br />  <span>if</span>(waitForResponse(<span>"setting data Length"</span>)){ <span>// Wait for an acknowledgement from the CH376S module before trying to send data to it</span><br />    <span>if</span>(getResponseFromUSB()==0x1E){ <span>// 0x1E indicates that the USB device is in write mode.</span><br />      USB.<span>write</span>(0x57);<br />      USB.<span>write</span>(0xAB);<br />      USB.<span>write</span>(0x2D);<br />      USB.<span>print</span>(data); <span>// write the data to the file</span><br />  <br />      <span>if</span>(waitForResponse(<span>"writing data to file"</span>)){ <span>// wait for an acknowledgement from the CH376S module</span><br />      }<br />      <span><b>Serial</b></span>.<span>print</span>(<span>"Write code (normally FF and 14): "</span>);<br />      <span><b>Serial</b></span>.<span>print</span>(USB.<span>read</span>(),<span>HEX</span>); <span>// code is normally 0xFF</span><br />      <span><b>Serial</b></span>.<span>print</span>(<span>","</span>);<br />      USB.<span>write</span>(0x57);<br />      USB.<span>write</span>(0xAB);<br />      USB.<span>write</span>(0x3D); <span>// This is used to update the file size. Not sure if this is necessary for successful writing.</span><br />      <span>if</span>(waitForResponse(<span>"updating file size"</span>)){ <span>// wait for an acknowledgement from the CH376S module</span><br />      }<br />      <span><b>Serial</b></span>.<span>println</span>(USB.<span>read</span>(),<span>HEX</span>); <span>//code is normally 0x14</span><br />    }<br />  }<br />}<br /><br /><span>//continueRead()==================================================================================</span><br /><span>//continue to read the file : I could not get this function to work as intended.</span><br /><span>boolean</span> continueRead(){<br />  <span>boolean</span> readAgain = <span>false</span>;<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x3B);<br />  <span>if</span>(waitForResponse(<span>"continueRead"</span>)){ <span>//wait for a response from the CH376S. If CH376S responds, it will be true. If it times out, it will be false.</span><br />     <span>if</span>(getResponseFromUSB()==0x14){ <span>//CH376S will send 0x14 if this command was successful</span><br />       readAgain=<span>true</span>;<br />     }<br />  }<br />  <span>return</span>(readAgain);<br />} <br /><br /><span>//fileCreate()========================================================================================</span><br /><span>//the command sequence to create a file</span><br /><span>boolean</span> fileCreate(){<br />  <span>boolean</span> createdFile = <span>false</span>;<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x34);<br />  <span>if</span>(waitForResponse(<span>"creating file"</span>)){ <span>//wait for a response from the CH376S. If file has been created successfully, it will return true.</span><br />     <span>if</span>(getResponseFromUSB()==0x14){ <span>//CH376S will send 0x14 if this command was successful</span><br />       createdFile=<span>true</span>;<br />     }<br />  }<br />  <span>return</span>(createdFile);<br />}<br /><br /><br /><span>//fileDelete()========================================================================================</span><br /><span>//the command sequence to delete a file</span><br /><span>void</span> fileDelete(<span>String</span> fileName){<br />  setFileName(fileName);<br />  <span>delay</span>(20);<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x35);<br />  <span>if</span>(waitForResponse(<span>"deleting file"</span>)){ <span>//wait for a response from the CH376S. If file has been created successfully, it will return true.</span><br />     <span>if</span>(getResponseFromUSB()==0x14){ <span>//CH376S will send 0x14 if this command was successful</span><br />       <span><b>Serial</b></span>.<span>println</span>(<span>"Successfully deleted file"</span>);<br />     }<br />  }<br />}<br />  <br /><br /><span>//filePointer========================================================================================</span><br /><span>//is used to set the file pointer position. true for beginning of file, false for the end of the file.</span><br /><span>void</span> filePointer(<span>boolean</span> fileBeginning){<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x39);<br />  <span>if</span>(fileBeginning){<br />    USB.<span>write</span>((<span>byte</span>)0x00); <span>//beginning of file</span><br />    USB.<span>write</span>((<span>byte</span>)0x00);<br />    USB.<span>write</span>((<span>byte</span>)0x00);<br />    USB.<span>write</span>((<span>byte</span>)0x00);<br />  } <span>else</span> {<br />    USB.<span>write</span>((<span>byte</span>)0xFF); <span>//end of file</span><br />    USB.<span>write</span>((<span>byte</span>)0xFF);<br />    USB.<span>write</span>((<span>byte</span>)0xFF);<br />    USB.<span>write</span>((<span>byte</span>)0xFF);<br />  }<br />  <span>if</span>(waitForResponse(<span>"setting file pointer"</span>)){ <span>//wait for a response from the CH376S. </span><br />     <span>if</span>(getResponseFromUSB()==0x14){ <span>//CH376S will send 0x14 if this command was successful</span><br />       <span><b>Serial</b></span>.<span>println</span>(<span>"Pointer successfully applied"</span>);<br />     }<br />  }<br />}<br /><br /><br /><span>//fileClose=======================================================================================</span><br /><span>//closes the file</span><br /><span>void</span> fileClose(<span>byte</span> closeCmd){<br />  <span><b>Serial</b></span>.<span>println</span>(<span>"Closing file:"</span>);<br />  USB.<span>write</span>(0x57);<br />  USB.<span>write</span>(0xAB);<br />  USB.<span>write</span>(0x36);<br />  USB.<span>write</span>((<span>byte</span>)closeCmd); <span>// closeCmd = 0x00 = close without updating file Size, 0x01 = close and update file Size</span><br /><br />  <span>if</span>(waitForResponse(<span>"closing file"</span>)){ <span>// wait for a response from the CH376S. </span><br />     <span>byte</span> resp = getResponseFromUSB();<br />     <span>if</span>(resp==0x14){ <span>// CH376S will send 0x14 if this command was successful</span><br />       <span><b>Serial</b></span>.<span>println</span>(<span>">File closed successfully."</span>);<br />     } <span>else</span> {<br />       <span><b>Serial</b></span>.<span>print</span>(<span>">Failed to close file. Error code:"</span>);<br />       <span><b>Serial</b></span>.<span>println</span>(resp, <span>HEX</span>);<br />     }  <br />  }<br />}<br /><br /><span>//waitForResponse===================================================================================</span><br /><span>//is used to wait for a response from USB. Returns true when bytes become available, false if it times out.</span><br /><span>boolean</span> waitForResponse(<span>String</span> errorMsg){<br />  <span>boolean</span> bytesAvailable = <span>true</span>;<br />  <span>int</span> counter=0;<br />  <span>while</span><!USB><span>available</span>()){ <span>//wait for CH376S to verify command</span><br />    <span>delay</span>(1);<br />    counter++;<br />    <span>if</span>(counter>timeOut){<br />      <span><b>Serial</b></span>.<span>print</span>(<span>"TimeOut waiting for response: Error while: "</span>);<br />      <span><b>Serial</b></span>.<span>println</span>(errorMsg);<br />      bytesAvailable = <span>false</span>;<br />      <span>break</span>;<br />    }<br />  }<br />  <span>delay</span>(1);<br />  <span>return</span>(bytesAvailable);<br />}<br /><br /><span>//getResponseFromUSB================================================================================</span><br /><span>//is used to get any error codes or messages from the CH376S module (in response to certain commands)</span><br /><span>byte</span> getResponseFromUSB(){<br />  <span>byte</span> response = <span>byte</span>(0x00);<br />  <span>if</span> (USB.<span>available</span>()){<br />    response = USB.<span>read</span>();<br />  }<br />  <span>return</span>(response);<br />}<br /><br /><br /><br /><span>//blinkLED==========================================================================================</span><br /><span>//Turn an LED on for 1 second</span><br /><span>void</span> blinkLED(){<br />  <span>digitalWrite</span>(LED, <span>HIGH</span>);<br />  <span>delay</span>(1000);<br />  <span>digitalWrite</span>(LED,<span>LOW</span>);<br />}<br /><br /></pre> </td> </tr> </table></div></p> <br /> <p> If you copy and paste this code directly into the Arduino IDE; you may get a warning like this when you compile the code:<br />   <br />    "Low memory available, stability problems may occur". <br />  <br /> I managed to run the sketch without any issues, however, I did experience problems with some of the methods when I had made further memory hungry modifications. If you do encounter problems, I would recommend that you eliminate any methods which you do not plan to use, and perhaps reduce the number of Serial.print statements throughout the code. However, please note that some of the methods will not work unless the module is in the correct state, so be careful which methods you delete. For example, I found that I could get some simple functionality without the "USBdiskMount()" method. However, I could not read/write data beyond a certain length without this method.<br />   <br /> Also please note, that some of the methods called within the reading and writing sequence do not need to be called every time. They can be called once in setup, while other methods within the sequence will need to be called every time. I grouped them all together for simplicity. </p> <!--separator --><img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <p><h4>Serial Commands</h4> Have a look at the following presentation for a summary of the Serial commands used in this tutorial: <br />   <br /> <div> </div> </p> </div><p> <div> <!-- Concluding Comments --> </div> <br />  <br />  <div> <p> <!--separator --> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p> </div> </p><p> <div> If you like this page, please do me a favour and show your appreciation : <br /> <br />  <br /> Visit my <a href="https://plus.google.com/u/0/b/107402020974762902161/107402020974762902161/posts">ArduinoBasics Google + page</a>.<br /> Follow me on Twitter by looking for <a href="https://twitter.com/ArduinoBasics">ScottC @ArduinoBasics</a>.<br /> I can also be found on <a href="https://www.pinterest.com/ArduinoBasics/">Pinterest</a> and <a href="https://instagram.com/arduinobasics">Instagram</a>. <br /> Have a look at my videos on my <a href="https://www.youtube.com/user/ScottCMe/videos">YouTube channel</a>.<br /> </div> </p> <br /> <div> <p> <!--separator --> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p> </div> <p> However, if you do not have a google profile... <br />Feel free to share this page with your friends in any way you see fit. </p>

A Tool For Spying On Serial Data

[Piotr] was working on a recent Arduino project when he ran into a problem. He was having trouble getting his Arduino Pro Mini to communicate with an ESP8266 module. He needed a way to snoop on the back and forth serial communications. Since he didn’t have a specialized tool for this task, [Piotr] ended up building his own.

The setup is pretty simple. You start with a standard serial cable containing the TX, RX, DTR, and GND wires. This cable connects the Arduino to the ESP8266 WiFi module. The TX and RX lines are then tapped into. Each wire is routed to the RX pin of two different serial to USB adapters. This way, the data being sent from the Arduino shows up on one COM port and the data being transmitted from the module shows up on the other.

The next piece of the puzzle was coming up with a way to see the data more clearly. [Piotr] could have opened two serial terminals simultaneously, but this wasn’t ideal because it would be difficult to compare the timing of the data. Instead, [Piotr] spent less than an hour writing his own simple serial terminal. This one connects to two COM ports at the same time and prints the data on the same screen. The data from each COM port is displayed in a separate color to make it easy to differentiate. The schematic and source code to this project can be found on [Piotr’s] website.


Filed under: Arduino Hacks, Microcontrollers