|  | 
 
| 本帖最后由 blackblue 于 2014-1-15 10:55 编辑 
 经过了N多次,几乎试了所有NXC扩展固件,标准固件,包括了试了所有有关NXC中关于RS485的功能函数,终于得到一个相对稳定的代码,
 拿出来和大家共享,以求为本坛增加一点流量和人气,欢迎下载试用,有不明白的请跟贴提问。为了这几行代码,前前后后一共浪费了我二个月业余的晚上的时间,为此老婆骂,孩子怨!NXC的高阶485函数,压根就是摆设(也可能是我NXT机器的问题),只能发送,却不能接收!
 另外的一个RS485发送数据,很简单,我以前的贴子中有(用高阶485发送函数是有效的,所以比较简单)。
 
 (注:什么你不知道这个东西的用处吗?我的初衷是利用这个高速端口,让外部的任何具有TTL口的MCU与NXT主机进行通讯,目的是提高NXT的扩展功能。比如,我准备做的最高100HZ刷新的三轴姿态模块,姿态解算和滤波由外部MCU完成,并完成数据编码,通过TTL与NXT S4相连,NXT只是能以100HZ刷新取得这些数据并加以利用,做个用数字陀螺和加计作为姿态传感器的平衡车就不是什么问题了,而且效果应该不会比模拟陀螺的差!)
 
 本代码实验器材:
 
 NXT主机一个;
 电脑一台;
 USB转TTL模块一个;
 TTL转485模块一个;(这个我是自制的,能实现数据自动流向管理)
 
 代码贴在下面:
 
 
 // RS-485 receiver
 #include "NXCDefs.h"
 task main()
 {
 byte mlen ;
 byte i;
 byte outPtr = 0;
 byte inPtr = 0;
 string buffer;
 string msgReceived ;
 TextOut(0, LCD_LINE1, "receiver Msg Test");
 UseRS485();
 RS485Enable();
 RS485Uart(HS_BAUD_115200, HS_MODE_8N1);
 SetHSInputBufferInPtr(0);
 SetHSInputBufferOutPtr(0);
 Wait(MS_5);
 
 while (true)
 {
 ClearScreen();
 outPtr = inPtr;
 inPtr = HSInputBufferInPtr();
 // Wait for new message
 while(inPtr <= outPtr)
 {
 Wait(MS_2);
 inPtr = HSInputBufferInPtr();
 }
 // Wait for whole message to arrive
 Wait(MS_3);
 // Take message out of buffer
 inPtr = HSInputBufferInPtr();
 mlen = inPtr-outPtr;
 GetHSInputBuffer(outPtr,mlen,msgReceived);
 buffer = SubStr(msgReceived,0,mlen) ;
 //if(SubStr(buffer,0,1) == "#")
 //..... Determine the data header bytes,
 // each byte of data into the array to remove, and then converted,
 //in addition omitted.
 
 // display message
 
 TextOut(0, LCD_LINE3, buffer);
 TextOut(0, LCD_LINE5,"buf_len");
 NumOut(25, LCD_LINE5,mlen);
 TextOut(0, LCD_LINE7,"inPtr=");
 TextOut(40, LCD_LINE7,"outPtr=");
 NumOut(25, LCD_LINE7,inPtr);
 NumOut(58, LCD_LINE7,outPtr);
 
 // clear the incoming buffer
 //According to the definition of a numeric variable data length,
 //I pass by every 10 bytes or 100 bytes to try,
 //so set the value of the variable is 100.
 if(HSInputBufferInPtr()>100)
 {
 RS485Enable();
 SetHSInputBufferInPtr(0);
 SetHSInputBufferOutPtr(0);
 Wait(MS_3);
 outPtr = 0;
 inPtr = 0;
 ClearScreen();
 }
 Wait(MS_500);//This is in order to successfully display also possible without
 }
 }
 
 
 
 
 加上TTL-485转换(有数据自动流向管理)原理图
 
 
  
 
 | 
评分
查看全部评分
 |